我是 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
产品控制器
定义新
@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>