【问题标题】:Can't access field through 3 models in Rails 5无法通过 Rails 5 中的 3 个模型访问字段
【发布时间】:2018-12-21 17:19:35
【问题描述】:

我正在尝试做一些与question非常相似的事情

我有 4 个模型,其中一个 (CoffeeBlend) 是一个连接表:

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

我的coffee_beans 表有一个名为country_id 的列,其中填充了countries 表中的ID。

在我的coffee_roasts_show我希望能够拉出咖啡豆的关联国家。我最近的尝试看起来像

<% @coffee_roast.coffee_beans.country.country_name %>

这给了undefined method 'country'

或者

<% @coffee_roast.coffee_beans.countries.country_name %>

返回undefined method 'countries'

我的关联是否正确?我的节目代码错了吗?

【问题讨论】:

    标签: ruby-on-rails model-associations


    【解决方案1】:

    @coffee_roast.coffee_beans 方法返回关联,而不是一条记录。这就是为什么你不能打电话给#country。如果需要所有国家,可以使用#map

    <% @coffee_roast.coffee_beans.map {|cb| cb.country.country_name } %>
    

    编辑:

    如果您想在浏览器中显示该列表,请将= 添加到您的 ERB 标记:

    <%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name } %>
    

    使用Array#join 将国家名称显式转换为字符串也可能很有用

    <%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name }.join(', ') %>
    

    【讨论】:

    • 我只需要一个国家。
    • 你有多个咖啡豆,哪一个给你国家?
    • coffee_blends 连接表中我有咖啡豆id 和bean id。
    • 每个coffee_roast 仍然有多个coffee_blends。您想展示哪个国家/地区?
    • 只是在终端中查看,使用上面的代码后,我可以看到,现在正在通过 country_id,但我没有在浏览器中写入任何内容。
    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多