如何使用has_many:through保存额外的字段值

时间:2013-03-22 07:01:34

标签: ruby-on-rails-3 has-many-through

我有这些模型

class Product < ActiveRecord::Base
  # fields: name, weight, expiry_date, active...

  has_many :categorizations
  has_many :categories, :through => :categorizations
end

class Category < ActiveRecord::Base
  # fields: name, active...

  has_many :categorizations
  has_many :products, :through => :categorizations
end

class Categorization < ActiveRecord::Base
  # fields: user_id, type, priority, product_id, category_id...

  belongs_to :product
  belongs_to :category

  validates :user_id, :presence =>  { :message => "Must be filled" }
end

_form.html.erb

<%= form_for @product do |f| %>
    <%= f.error_messages %>
    <%= f.text_field :name %>
    <%= f.select :category_ids .... {:multiple => true} %>
<% end %>

参数:

{"product"=>{"name"=>"sdf", "category_ids" => ["1", "2"]}, "commit"=>"Create Product"}

问题:如何保存某些其他字段,例如user_id,分类表中的优先级?

我在初始化产品后尝试访问分类对象,但是有空数组。例如

@product = Product.new(params[:product]) # {"product"=>{"name"=>"sdf", "category_ids" => ["1", "2"]}, "commit"=>"Update Document"}
@product.categorizations => []

0 个答案:

没有答案