Can't access field through 3 models in Rails 5

廉价感情. 提交于 2020-02-05 03:49:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!