Ruby on rails 如何使用嵌套窗体外部的嵌套窗体的字段作为";全局字段“;?
如果我有以下关联的模型:Ruby on rails 如何使用嵌套窗体外部的嵌套窗体的字段作为";全局字段“;?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,如果我有以下关联的模型: class Business has_many :products class Product belongs_to :business 我在控制器中生成3个产品: def new @business = Business.new 3.times do @business.products.build end end 使我的表单如下所示: <%= form_for @business do |f| %> <% f.te
class Business
has_many :products
class Product
belongs_to :business
我在控制器中生成3个产品:
def new
@business = Business.new
3.times do
@business.products.build
end
end
使我的表单如下所示:
<%= form_for @business do |f| %>
<% f.text_field :business_name %>
<%= f.fields_for :products do |pf| %> # x2 more products generated
<% pf.text_field :name %>
<% pf.text_field :price %>
<% pf.text_field :date %>
<% end %>
#生成更多产品
如果我想让其中一个字段作为其他产品的全局字段,我怎么能将像:price
这样的字段放在f.fields\u for:products
之外,让它成为所有产品的:price
谢谢。如果需要初始化价格,请在控制器中进行初始化。但如果需要不直接映射到模型的字段,请使用常规表单帮助程序:
<%= text_field_tag 'global_price' %>
或者,您可以在业务模型中定义一种方法:
def global_price=
#do something with the global price, such as updating child object...
# I'm not sure if the child form objects have been instantiated yet though
end
然后,您可以在业务表单中使用它:
<%= f.text_field :global_price %>
这使得它成为一个实例变量。然后可以使用“保存前”过滤器更新子对象
before_save :update_global_price
def update_global_price
#do something with @global_price
end
如果需要初始化价格,请在控制器中进行初始化。但如果需要不直接映射到模型的字段,请使用常规表单帮助程序:
<%= text_field_tag 'global_price' %>
或者,您可以在业务模型中定义一种方法:
def global_price=
#do something with the global price, such as updating child object...
# I'm not sure if the child form objects have been instantiated yet though
end
然后,您可以在业务表单中使用它:
<%= f.text_field :global_price %>
这使得它成为一个实例变量。然后可以使用“保存前”过滤器更新子对象
before_save :update_global_price
def update_global_price
#do something with @global_price
end