Issue
I have 2 models ("Offence" and "OffenceType") with a has_many relationship managed by a join table "lk_offence_types".
In the index.html.erb of "Offence" I'm not able to display an OffenceType item. (I've tried with delegation but it seems not work with has_many..)
Offence model:
class Offence < ApplicationRecord
has_many :lk_offence_types, inverse_of: :offence, dependent: :destroy
has_many :offence_types, through: :lk_offence_types
#delegate :offence_type_description, to: :offence_type
end
OffenceType model:
class OffenceType < ApplicationRecord
has_many :lk_offence_types
has_many :offences, through: :lk_offence_types
end
LkOffenceType model:
class LkOffenceType < ApplicationRecord
belongs_to :offence_type, inverse_of: :lk_offence_types
belongs_to :offence, inverse_of: :lk_offence_types
end
Offence's index.html.erb:
<% @offences.each do |offence| %>
<tr>
<td><%= offence.offence_description %></td>
<td><%= offence.offence_types.offence_type_description %></td>
<% end %>
<%= offence.offence_types.offence_type_description %> gives me an error. I've also tried with: <%= offence.offence_type_description %> and other siyntaxes...
What am I missing?
(I'm using Ruby 2.3 and Rails 5.0.2)
Thanks
Solution
You need to loop over offence types
as well. You may need to fix the styling, this is just to give you the idea of what's missing.
<% offence.offence_types.each do |ot| %>
<td><%= ot.offence_type_description %></td>
<% end %>
Answered By - Eyeslandic Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.