【问题标题】:How to use variable named scopes with attributes of associated models OTHER than id如何使用具有关联模型属性的变量命名范围而不是 id
【发布时间】:2010-04-09 16:08:44
【问题描述】:

我在使用关联模型的属性而不是 id 列来使命名范围工作时遇到问题。

我有一个包含 city_id 列的公司模型。 我还有一个带有名称列的城市模型。

我想获得这样的 url,以便利用 has_scope gem 并拥有瘦控制器

http://localhost:3000/firms?by_city=Dublin

但是使用当前代码我只能插入城市 ID

http://localhost:3000/firms?by_city=546

这是我的named_route

class Firm < ActiveRecord::Base       
named_scope :by_city, proc {|city| { :conditions => { :city => city } } }
end

任何关于如何修改命名范围以使用该名称生成 url 的想法将不胜感激!

谢谢,

杰克

【问题讨论】:

    标签: ruby-on-rails associations named-scope


    【解决方案1】:

    您需要将belongs_to 添加到公司类,然后为命名范围添加一个城市连接,以便您可以在查询中获取城市名称。像这样的

    class Firm < ActiveRecord::Base
      belongs_to :city
      named_scope :by_city, lambda {|city_name| {:joins => :city, :conditions => {:city => {:name => city_name}}}}
    end
    

    【讨论】:

    • 谢谢 - 这可行,但需要稍作修改 named_scope :by_city, lambda {|city_name| {:joins => :city, :conditions => {:cities => {:name => city_name}}}}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多