问题
I'm trying to do something very similar to this question
I have 4 models, one of which (CoffeeBlend) is a join table:
class CoffeeRoast < ApplicationRecord
has_many :coffee_blends
has_many :coffee_beans, through: :coffee_blends
has_one :country, through: :coffee_beans
end
class CoffeeBean < ApplicationRecord
has_many :coffee_blends
has_many :coffee_roasts, through: :coffee_blends
belongs_to :country
end
class Country < ApplicationRecord
has_many :coffee_beans
end
class CoffeeBlend < ApplicationRecord
belongs_to :coffee_bean
belongs_to :coffee_roast
end
My coffee_beans
table has a column called country_id
which is populated with the id from the countries
table.
In my coffee_roasts_show
I want to be able to pull the associated country of the coffee bean. My latest attempt looks like
<% @coffee_roast.coffee_beans.country.country_name %>
which gives undefined method 'country'
Or
<% @coffee_roast.coffee_beans.countries.country_name %>
returns undefined method 'countries'
Do I have my associations correct? Is my show code wrong?
回答1:
The method @coffee_roast.coffee_beans
returns you association, not a single record. That's why you cannot call #country
on that. If you need all the countries, you can use #map
:
<% @coffee_roast.coffee_beans.map {|cb| cb.country.country_name } %>
Edit:
If you want to show the list in the browser, add =
to your ERB mark:
<%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name } %>
It may also be useful to explicitly convert contry names to a string with Array#join
<%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name }.join(', ') %>
来源:https://stackoverflow.com/questions/53888615/cant-access-field-through-3-models-in-rails-5