0

My Category model :

class Category < ActiveRecord::Base
    has_many :item_categoryships
    has_many :items, :through => :item_categoryships
end

My Item model :

class Item < ActiveRecord::Base
    has_many :item_categoryships
    has_many :categories, class_name: 'ItemCategoryship', foreign_key: 'category_id', :through => :item_categoryships

end

My ItemCategoryship model:

class ItemCategoryship < ActiveRecord::Base
    belongs_to :item
    belongs_to :category
end

And in views/items/edit.html.erb, I wrote simple form code like this:

<%= simple_form_for(@item) do |f| %>
    <%= f.association :categories, collection: @categories, as: :check_boxes %>
    <%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>

The @categories above, I wrote this in controller:

@categories = current_user.categories

But I hit a problem, they can't save to database!!

I couldn't find out what the problem was. Please help me.... Thanks you all.

user3087000
  • 731
  • 1
  • 13
  • 24
  • can you access `category.items` in the rails console? – benjaminjosephw Dec 10 '13 at 13:51
  • Sorry....If that needs a controller to handle create action and desrtoy action? I only have created one minimal Rails website, I can't get a idea how can I handle check_boxes.... – user3087000 Dec 10 '13 at 14:16
  • What relationship between these two models are you trying to create. Are you trying to assign an item to a category (i.e. one category per item)? A check box would not be the way to achieve this, but before you tackle that problem, you may need to work on the associations in the models themselves. – benjaminjosephw Dec 10 '13 at 14:27
  • I want one item can have many categories... – user3087000 Dec 10 '13 at 14:30
  • then maybe you don't need `has_many :through` - `Category` should use the `belongs_to` association. http://guides.rubyonrails.org/association_basics.html – benjaminjosephw Dec 10 '13 at 14:39

1 Answers1

0

For the view, this SO answer should help: https://stackoverflow.com/a/9917006/2463468

You may first need to make sure your associations make sense. Perhaps you only need a has_many on Items and belongs_to on Category.

You might be able to do without ItemCategoryship.

Community
  • 1
  • 1
benjaminjosephw
  • 4,369
  • 3
  • 21
  • 40