P.H.
P.H.

Reputation: 481

How to reference join table columns from a rails index.html.erb view

I have 3 Rails 4.2 tables: books, tags, categorizations where categorizations is a many to many join table for the other two.

Inside the show.html.erb file, I can say

<%= @categorization.book.title %>

and the book title will be displayed, but inside index.html.erb, if I say something similar like

<%= categorizations.each do |categorization| %>
<%= categorization.book_id %> # this is ok
<%= categorization.book.title %> # not ok
 ...
<% end %>

The error message is

undefined method `title' for nil:NilClas

I'm sure there is a way to get rails to do this, but I am not doing it right. Is there a way to ask the controller to do a join using all three tables instead of just the join table? Or do I need to instantiate a book object inside the loop (sounds ugly, but ...)?

Upvotes: 0

Views: 780

Answers (1)

Brian S
Brian S

Reputation: 5785

It sounds like you're missing the ActiveRecord Associations in your models. In order to have a book accessor on your categorization model, you would need to define the association in the models. From what you say above, it sounds like you would want to create a has_many :through association.

See the Active Record Associations documentation for more details. I imagine it would look something like this:

class Book < ActiveRecord::Base
  has_many :categorizations
  has_many :tags, through: :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :book
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :categorizations
  has_many :books, through: :categorizations
end

Once you have the associations in place, you should be able to do @categorization.book without issue.

Upvotes: 1

Related Questions