我通过分类有一个项目和类别的关联:
class Item < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations, :source => :category
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :items, :through => :categorizations, :source => :item
attr_accessible :name
end
class Categorization < ActiveRecord::Base
belongs_to :item
belongs_to :category
end
物品/新品:
<div class="container">
<%= render 'shared/error_create_item_messages'%>
<br/>
<%= form_for(@item, :html => {:multipart => true} ) do |f| %>
<div class="clearfix">
<label>
<%= f.label :name %>
</label>
<div class="input">
<%= f.text_field :name %>
</div>
</div>
<div class="clearfix">
<label>
<%= f.label :category %>
</label>
<%= hidden_field_tag "product[category_ids][ ]", nil %>
<% Category.all.each do |category| %>
<div class="input">
<%= check_box_tag "item[category_ids][ ]", category.id,
@item.category_ids.include?(category.id) %>
<%= category.name %>
</div>
<% end %>
</div>
<div class="action">
<div class="btn_create_item_align">
<%= f.submit "Create item", :class=>"btn primary" %>
</div>
</div>
<% end %>
</div>
分类_控制器
class CategorizationsController < ApplicationController
def create
@categories = Category.all
Categorization.create(:item_id => item.id, :category_id => category.id)
Categorization.save
end
def edit
end
end
Items_controller
def create
@item = @current_user.items.build(params[:item])
@categories = Category.all
if @item.save
redirect_to @item
else
render 'new'
end
end
问题是当我点击保存(创建项目)时,我检查分类表并检查控制台,保存的项目仍然没有 category_id。因此,新项目及其属性(名称、描述、价格)被正确保存到数据库,但不是类别。它不会保存到数据库。
有任何想法吗?(Rails 新手)谢谢