通过定义方法创建关联
您好,我在将此关联定义为 has_many 时遇到问题,我想这样做,以便使 Accepts_nested_attributes_for 正常工作。
def work_days
work_days = WorkDay.user_id_equals(self.user_id).company_id_equals(self.company_id)
end
accepts_nested_attributes_for :work_days
什么是好的解决方案?无论如何我可以说这是一个协会吗?
-- 导轨 3.0.7
Hi I'm having trouble defining this association as a has_many which I would like to do in order to get accepts_nested_attributes_for to work.
def work_days
work_days = WorkDay.user_id_equals(self.user_id).company_id_equals(self.company_id)
end
accepts_nested_attributes_for :work_days
What would be a good solution? Is there anyway I can just say that this is an association?
-- Rails 3.0.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我会像这样编写
work_days
方法:接下来,
accepts_nested_attributes_for
实际上仅适用于真实 关联,因此我会定义一个这样的方法:(我可能有错误的方法名称)
在您的表单中,您会看到类似这样的内容:
在该部分中,您将拥有工作日所需的一切。提交此表单后,参数应作为
params[:nest][:work_days]
发送到控制器,并使用模型上定义的work_days=
方法,它应该像accepts_nested_attributes_for
一样接受它们并创建它们。Firstly I would write the
work_days
method like this:Next,
accepts_nested_attributes_for
is really only for real associations, and so I would define a method like this:(I may have the method name wrong)
In your form you would have something like this:
In that partial you would have whatever is necessary for a work day. Once this form is submitted the params should be sent through to the controller as
params[:nest][:work_days]
and with thework_days=
method defined on your model, it should accept them and create them just likeaccepts_nested_attributes_for
does.