我在两个表之间建立了HABTM关系,在项目和类别之间创建了多对多的关系。我想通过添加项目表单添加与一个或多个类别相关联的项目。当我提交表单时,我收到错误"无法批量分配受保护的属性:类别"。
以下是我的模特:
class Item < ActiveRecord::Base
attr_accessible :description, :image, :name
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
belongs_to :user
has_and_belongs_to_many :categories
validates :name, presence: true, length: {maximum: 50}
accepts_nested_attributes_for :categories
end
class Category < ActiveRecord::Base
attr_accessible :description, :name
has_and_belongs_to_many :items
validates :name, presence: true, length: {maximum: 50}
end
我的迁移:
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :name
t.text :description
t.has_attached_file :image
t.timestamps
end
end
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
class CreateCategoriesItems < ActiveRecord::Migration
def up
create_table :categories_items, :id => false do |t|
t.integer :category_id
t.integer :item_id
end
end
def down
drop_table :categories_items
end
end
我的表格看起来像这样:
<%= form_for(@item, :html => { :multipart => true }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.file_field :image %>
<%= f.collection_select(:categories, @categories,:id,:name)%>
<%= f.submit "Add Item", :class => "btn btn-large btn-primary" %>
<% end %>
这是我的物品管理员:
class ItemsController < ApplicationController
def new
@item = Item.new
@categories = Category.all
end
def create
@item = Item.new(params[:item])
if @item.save
#sign_in @user
flash[:success] = "You've created an item!"
redirect_to root_path
else
render 'new'
end
end
def show
end
def index
@items = Item.paginate(page: params[:page], per_page: 3)
end
end
感谢您的所有帮助:)
-Rebekah
答案 0 :(得分:2)
批量分配通常意味着将属性传递给调用,该调用将对象创建为属性哈希的一部分。
试试这个:
@item = Item.new(name: 'item1', description: 'description1')
@item.save
@category = Category.find_by_name('category1')
@item.categories << @category
另见:
http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html
我希望这会有所帮助。
答案 1 :(得分:1)
IAmNaN发布了上面的评论,这是我的代码中正常工作的缺失链接。我已经编写了blog post,详细说明了获取HABTM设置的过程。谢谢IAmNaN!