Note that there are some explanatory texts on larger screens.

plurals
  1. POConfused about Rails has_and_belongs_to_many Association
    primarykey
    data
    text
    <p>I have two models, items and categories which have a many-to-many relationship using the has_and_belongs_to_many association.</p> <p>In my models I have</p> <pre><code>class Item &lt; ActiveRecord::Base has_and_belongs_to_many :categories end </code></pre> <p>and </p> <pre><code>class Category &lt; ActiveRecord::Base has_and_belongs_to_many :items end </code></pre> <p>I created a join table "categories_items":</p> <pre><code>create_table "categories_items", :id =&gt; false, :force =&gt; true do |t| t.integer "category_id" t.integer "item_id" end </code></pre> <p>I'm not getting any errors, but I'm just a bit confused about exactly what the association allows. Right now, if I have some category @category, I can find all the Items in it by doing </p> <pre><code>@category.items </code></pre> <p>I assumed that I could find the categories associated with a given Item @item by doing</p> <pre><code>@item.categories </code></pre> <p>However I get an error that says ActiveModel::MissingAttributeError: missing attribute: category</p> <p>Am I misunderstanding how a has_and_belongs_to_many association functions, or am I missing something in my code? Thank you!</p> <p>Edit - Additional Information:</p> <p>I think the confusion lies in how I'm supposed to assign items/categories. Currently, I'm creating them independently: </p> <pre><code>@item = Item.new ... add attributes ... @item.save </code></pre> <p>and </p> <pre><code>@category = Category.new ... add attributes ... @category.save </code></pre> <p>and then associating them with</p> <pre><code>@category.items &lt;&lt; @item @item.categories &lt;&lt; @category </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload