【问题标题】:scope not working in relationship范围在关系中不起作用
【发布时间】:2014-09-02 14:31:15
【问题描述】:

我的模特:

class House
belongs_to: country
scope :published, -> { where(published: true) }
end

class Country
has_many: houses
end

我想展示已出版的来自 x 国的房屋;

house_controller:

@country = Country.friendly.find(params[:country_id])
@houses = @country.houses.published.order(:sorting)

我收到错误“未定义的方法`已发布”

我做错了什么?

【问题讨论】:

  • 在控制台,能不能成功做House.published
  • 如果@countrynil,我敢打赌你会得到“为 NilClass '发布'的未定义方法”或类似的东西,这完全有道理。 @country 是零吗?
  • 你的模型不好看我看不到ActiveRecord::Base请正确发布

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1


【解决方案1】:

您可以使用以下发布的范围:

House.where(country_id: @country.id).published.order(:sorting)

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多