如何将数组传递给 Rails 中的 fields_for?

发布于 2024-09-17 07:48:52 字数 348 浏览 14 评论 0原文

我想对关联中的记录子集使用 fields_for

我有一个 Month 模型,它 has_many : payments

但在我看来,在我的表单中,我只想获得其中一些付款的fields_for。例如:

- fields_for @month.payments.large

这不起作用。

我可以将一组记录传递给 fields_for,而不是通常的符号 (fields_for : payments) 方法吗?

I want to use fields_for on a subset of records in an association.

I have a Month model, which has_many :payments.

But in my form in my view I only want to have fields_for some of those payments. For example:

- fields_for @month.payments.large

This doesn't work.

Can I pass a set of records to fields_for, rather than the usual symbol (fields_for :payments) approach?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

毅然前行 2024-09-24 07:49:54

但是,您可以使用对象数组,而无需创建任何其他关联。例如,假设在您的控制器中您准备了一些 @large_ payments 数组,那么在视图中您可以执行以下操作:

<%= f.fields_for :payments, @large_payments do |payment| %> ...

这样,如果您有一个相当大的表单或多页表单,并且您不希望必须为要显示的每个组创建额外的关联,但您不必这样做。

You can, however, use an array of objects without having to create any additional associations. For example, let's say that in your controller you prepared some array of @large_payments, then in the view you can do the following:

<%= f.fields_for :payments, @large_payments do |payment| %> ...

That way if you've got a pretty big form or multiple pages of forms, and you don't want to have to create an additional association for each group that you want to display, you don't have to.

白衬杉格子梦 2024-09-24 07:49:43

您可以为大额付款添加额外的关联,例如:

class Month < ActiveRecord::Base
  has_many :payments
  has_many :large_payments, :class_name => "Payment", :conditions => "value > 1000000"
end

之后您可以以常见的方式使用 fields_for

- fields_for :large_payments

我认为将此逻辑封装在模型端是比在视图中更好的方法。

You can add additional association for large payments, for example:

class Month < ActiveRecord::Base
  has_many :payments
  has_many :large_payments, :class_name => "Payment", :conditions => "value > 1000000"
end

After that you can use fields_for in common way:

- fields_for :large_payments

I think to encapsulate this logic on a model side is a better approach then in the view.

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