ruby on rails - How do I add a data association between records in a HABTM many to many relationship? -
i have set habtm relationship between 2 table creating many many relationship between items , categories. want add item connected 1 or more categories via add item form. when submit form getting error "can't mass-assign protected attributes: categories".
here models:
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
and migrations:
class createitems < activerecord::migration def change create_table :items |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 |t| t.string :name t.string :description t.timestamps end end end class createcategoriesitems < activerecord::migration def create_table :categories_items, :id => false |t| t.integer :category_id t.integer :item_id end end def down drop_table :categories_items end end
and form looks this:
<%= form_for(@item, :html => { :multipart => true }) |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 %>
and here's items controller:
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 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
thanks of :)
-rebekah
mass assignment means passing attributes call creates object part of attributes hash.
try this:
@item = item.new(name: 'item1', description: 'description1') @item.save @category = category.find_by_name('category1') @item.categories << @category
also see:
http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association http://api.rubyonrails.org/classes/activemodel/massassignmentsecurity/classmethods.html
i hope helps.
Comments
Post a Comment