我&范畴的分类项目的关联:的has_many:通过将不保存到数据库
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>
Categorizations_controller
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。 因此,新项目及其属性(名称,说明,价格)已正确保存到数据库,但不是类别。它不会保存到分贝。
任何想法? (Newbie in Rails) 谢谢
你的控制器的创建动作是什么样的? – rkb 2011-12-30 05:14:14
Hi @rkb,刚刚编辑添加控制器。我希望它能帮助我解决这个问题。 – imseto 2011-12-30 06:40:57