我刚开始使用rails并在rails应用程序上工作,我一直在思考这个问题。
我有三个模特
class Product < ActiveRecord::Base
attr_accessible :name, :issn, :category, :user_products_attributes
validates_presence_of :name, :issn, :category
validates_numericality_of :issn, :message => "has to be a number"
has_many :user_products
has_many :users, :through => :user_products
accepts_nested_attributes_for :user_products
end
class UserProduct < ActiveRecord::Base
attr_accessible :price, :category
validates_presence_of :price, :category
validates_numericality_of :price, :message => "has to be a number"
belongs_to :user
belongs_to :product
end
class user < ActiveRecord::Base
# devise authentication here
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :user_products, :dependent => :destroy
has_many :products, :through => :user_products
end
产品控制器
def new
@product = product.new
@product.user_products.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
端
所以问题是这样的:我希望用户在表单中输入产品的信息,但它还涉及存在与产品相关的不同模型/表(user_product)中存在的产品的价格。我怎样才能做到这一点?您可以看到我的form_for使用@product。
任何帮助将不胜感激。
<div class="span8">
<div id="listBoxWrapper">
<fieldset>
<%= form_for(@product, :html => { :class => "form-inline" }, :style => "margin-bottom: 60px" ) do |f| %>
<div class="control-group">
<label class="control-label" for="Category">Category</label>
<div class="controls">
<%= f.text_field :category, :class => 'input-xlarge', :id => "Category" %>
</div>
</div>
<div class="control-group" style="display: inline-table;">
<label class="control-label" for="First Name">Price($/Month)</label>
<div class="controls">
<%= product.fields_for :user_products do |p| %>
<%= p.text_field :price, :class => 'input-xlarge input-name' %>
<% end %>
</div>
</div>
答案 0 :(得分:2)
应该是以下
<%= form_for(@product) do |product| %>
<%= product.text_field :name, :class => 'input-xlarge input-name' %>
<%= product.fields_for :user_products do |user_product| %>
<%= user_product.text_field :price, :class => 'input-xlarge input-name' %>
您需要为控制器中的user_products
构建@product
。像
@product.user_products.build
并且您的Product
模型应具有以下内容
accepts_nested_attributes_for :user_products
这将使其意识到在保存产品实体时可能会出现user_products
值。
修改强>
只是解释嵌套表格的骨架
form_for(@object) do |object_form_builder|
# call any field generator helper function by object_form_builder like
object_form_builder.text_field
object_form_builder.check_box
# so on...
#Now for nested forms get the nested objects from the builder like
object_form_builder.fields_for :nested_objects do |nested_object_builder|
#generate the fields for this with nested_object_builder. Like
nested_object_builder.text_field
# so on...
end
end
是的,对于对象构建器使用短名称总是很方便,就像通常使用f
form_builder
一样。