[英]Ruby on Rails: how do I create an initializer method in the model or should I set all the default params in a controller?
I have a field in my model for date created, this is not passed from the form and is currently set in the create method of my controller. 我的模型中有一个用于创建日期的字段,该字段未从表单传递,并且当前在控制器的create方法中设置。
Should this be in my model instead in some sort of initializer method? 这应该在我的模型中,而不是某种初始化方法中吗? If so what would that method look like?
如果是这样,该方法将是什么样?
I have other fields I want to set as a default each a record is created so I'm trying to find out where is the accepted standard place to put these. 我还有其他要设置为默认值的字段,每条记录都会被创建,因此我试图找出放置这些内容的可接受的标准位置。 I'm starting to think it should be the model as if the model was ever called outside the controller it wouldn't have all this logic.
我开始认为它应该是模型,就像该模型曾经在控制器外部被调用一样,它并没有所有的逻辑。
I generally create builders and never use directly the standard Rails method create
. 我通常会创建构建器,并且永远不会直接使用标准的Rails方法
create
。
The point is to gather all the logic in one place with particular cases etc... 关键是将所有逻辑和特定案例等集中在一处...
Basically in controllers I end up calling the builders this way: 基本上在控制器中,我最终以这种方式调用构建器:
@my_model_instance = MyModelBuilder.new(current_user, params[:my_model]).build
@my_model_instance = MyModelBuilder.new(current_user, params[:my_model]).create
All my builders live in /app/builders
我所有的建设者都住在
/app/builders
Here is a very basic example: 这是一个非常基本的示例:
class MyModelBuilder
attr_accessor :params, :user, :my_model
# consider using a Struct if you keep a very basic initializer
def initialize(user, params)
self.user = user
self.params = params
end
def build
my_model
end
def create
my_model.tap{|m| m.save }
end
def my_model
@my_model ||= MyModel.new(default_values.merge(params))
end
def default_values
{
foo: 'bar'
}
end
end
Rails already manages the date of creation and update of your records. Rails已经管理着记录的创建和更新日期。
If your model has a created_at
field or an updated_at
field they will be filled with the time of creation and update of your model. 如果您的模型具有
created_at
字段或updated_at
字段,则将使用创建和更新模型的时间来填充它们。
You can generate those fields easily in a migration, for instance : 您可以在迁移中轻松生成这些字段,例如:
create_table :hello do
t.timestamps
end
Now, for default values, you can fill them in the initialize
method of the model : 现在,对于默认值,您可以将它们填充到模型的
initialize
方法中:
def initialize(*args)
self.field = default_value
super(*args)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.