[英]Building a rails Model using initialize
I have a model like so: 我有一个像这样的模型:
class Phrase < ActiveRecord::Base
attr_accessible :phrase, :emotion, :category
end
This model corresponds to it's appropriate table. 该模型对应于它的适当表。 Every time I want to create a new
Phrase
, I run this code in a controller: 每当我想创建一个新的
Phrase
,我都会在控制器中运行以下代码:
Phrase.where(:phrase => values['phrase']).first_or_create do |phrase|
phrase.emotion = values['emotion']
phrase.category = values['category']
end
I feel like I should be using the initialize method on my model, or perhaps creating a new method on my model to build them up. 我觉得我应该在模型上使用initialize方法,或者也许在模型上创建一个新方法来建立它们。 The above method seems pretty bad, especially when I start building models with 20+ attributes.
上面的方法似乎很糟糕,尤其是当我开始构建具有20多个属性的模型时。
Is there a best/better practice around building models? 是否有关于构建模型的最佳/最佳实践? Should the above controller code actually live in the model somewhere?
上面的控制器代码是否应该实际存在于模型中的某个位置?
Since your model allows for mass assignment of those attributes via attr_accessible
you can just pass a hash to new
: 由于您的模型允许通过
attr_accessible
大规模分配这些属性, attr_accessible
您只需将哈希传递给new
:
Phrase.new(values)
You can also use find_or_create_by
with a hash of options: 您还可以将
find_or_create_by
与选项哈希一起使用:
Phrase.find_or_create_by_phrase(values[:phrase], values)
def create
@phrase = Phrase.new(params[:phrase])
end
or if you are using strong parameters 或者如果您使用的参数很强
def create
@phrase = Phrase.new(phrase_params)
end
private
def phrase_params
params.require(:phrase).permit(:phrase, :emotion, :category)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.