通过定义方法创建关联

发布于 2024-11-03 16:46:30 字数 308 浏览 1 评论 0原文

您好,我在将此关联定义为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渔村楼浪 2024-11-10 16:46:30

首先,我会像这样编写 work_days 方法:

def work_days
  WorkDay.where(:user_id => user_id, :company_id => company_id)
end

接下来,accepts_nested_attributes_for 实际上仅适用于真实 关联,因此我会定义一个这样的方法:(

def work_days=(work_day_params)
  # iterate over work_day_params and define new work day objects as required
end

我可能有错误的方法名称)

在您的表单中,您会看到类似这样的内容:

<% f.fields_for :work_days do |work_day| %>
  <%= render :partial => "work_days/fields", :locals => { :f => work_day } %>
<% end %>

在该部分中,您将拥有工作日所需的一切。提交此表单后,参数应作为 params[:nest][:work_days] 发送到控制器,并使用模型上定义的 work_days= 方法,它应该像 accepts_nested_attributes_for 一样接受它们并创建它们。

Firstly I would write the work_days method like this:

def work_days
  WorkDay.where(:user_id => user_id, :company_id => company_id)
end

Next, accepts_nested_attributes_for is really only for real associations, and so I would define a method like this:

def work_days=(work_day_params)
  # iterate over work_day_params and define new work day objects as required
end

(I may have the method name wrong)

In your form you would have something like this:

<% f.fields_for :work_days do |work_day| %>
  <%= render :partial => "work_days/fields", :locals => { :f => work_day } %>
<% end %>

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 the work_days= method defined on your model, it should accept them and create them just like accepts_nested_attributes_for does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文