我想通过一个表单接收一些User数据,然后用我的User分析其中的一些数据。rb的方法。如果数据返回true,我想创建一个新的Hipster记录。
我只有想保存Hipster记录,而不是User记录。通用用户记录对我来说是无用的。
最简单的方法是使用一个Hipster模型,并在保存之前创建一堆自定义验证。下面是我当前的代码:
Hipster.rb
validate :hipster_status, :on => :create
def hipster_status
has_a_bike?
has_a_moustache?
has_skinny_jeans?
unless hipster?
self.errors.add("aint a hipster")
end
end
def has_a_bike?
# run some code to see if User has a bike
end
def has_a_moustache?
# run some code to see if User has a moustache
end
def has_skinny_jeans?
# run some code to see if User has skinny jeans
end
def hipster?
has_a_bike? && has_a_moustache? && has_skinny_jeans?
end
但是在Hipster模型中使用这些方法感觉是错误的。调用hipster.hipster?
感觉很奇怪,我觉得我应该创建一个临时用户,然后调用user.hipster?
,如果它返回true,然后创建一个Hipster(甚至不保存用户)。
但是我很难想象新的建筑。当用户访问user# new页面时,他们向user# create ?但我不想创建User。在不打算创建记录的情况下发布到用户#create是否可以?
或者我只是想多了,应该坚持第一个版本?我同意roger的评论。如果你的用户有很多附件或其他额外属性,那就创建一个相关的模型。
如果自行车、胡子和紧身牛仔裤是你唯一感兴趣的东西,并且你正在使用一个像Postgres这样支持数组序列化的数据库,你可以做一些更简单的事情,像这样:
class User < ActiveRecord::Base
# add a text column to the users table named accessories
serialize :accessories, Array
def has_accessory(accessory_name)
accessories.include? accessory_name
end
def is_hipster?
has_accessory('bike') && has_accessory('mustache') && has_accessory('skinny jeans')
end
end