【发布时间】:2012-08-31 03:36:57
【问题描述】:
我是 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>
【问题讨论】:
-
我按照您的步骤和 railscast 教程进行操作。我已经编辑了上面的代码...现在我收到“未知属性:book_id”错误...我似乎认为我的 user_products 的命名约定错误...谢谢!
-
对不起,我的意思是 product_id...我想我现在可以工作了...我刚刚在我的 user_products 表中添加了一个 product_id...
-
一切正常...非常感谢!!!....不过我正在重新考虑我设置所有模型的方式..可能不是最好的方式...如果你在乎,我可以解释,也许您可以提供更好的方法。再次感谢
-
你为什么不...让我们看看:)
-
好酷...我会输入一些内容并在大约一个小时后发送...我可能需要展开另一个讨论。再次感谢
标签: ruby-on-rails ruby ruby-on-rails-3