2014-02-18 76 views
-1

我在我的項目有問題,我想加入2表(「用戶+國家) 我有下面的代碼嘗試,但它沒有工作,Ruby on Rails的範圍聯接表

class User < ActiveRecord::Base 

    belongs_to :country 

    scope :ind, joins(:countries).where("countries.name like %india%") 
end 

當我把這種方法,我發現了錯誤,如下面的代碼:

1.9.3-p484 :016 > user_ind = User.ind 
NoMethodError: undefined method `ind' for #<Class:0xaa5ed94> 
    from /home/vinra/.rvm/gems/[email protected]/gems/activerecord-3.2.14/lib/active_record/dynamic_matchers.rb:55:in `method_missing' 
    from (irb):16 
    from /home/vinra/.rvm/gems/[email protected]/gems/railties-3.2.14/lib/rails/commands/console.rb:47:in `start' 
    from /home/vinra/.rvm/gems/[email protected]/gems/railties-3.2.14/lib/rails/commands/console.rb:8:in `start' 
    from /home/vinra/.rvm/gems/[email protected]/gems/railties-3.2.14/lib/rails/commands.rb:41:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main>' 

我希望有人能幫助我,, 謝謝你的好意

+0

您可能沒有保存'user.rb'文件。 –

+0

或者不重新加載您的控制檯 – MikDiet

回答

7

正確的語法應爲:

scope :ind, -> { joins(:country).where("countries.name like %india%") } 

joins名字應該是協會的名稱,而不是從doc表:

主動記錄可讓您使用 模型中定義的關聯的名字作爲在使用聯接方法時爲那些 關聯指定JOIN子句的快捷方式。而不調用對象

範圍語法是deprecated

的棄用警告:使用#scope沒有通過一個可調用對象是 棄用。例如scope :red, where(color: 'red')應該是 更改爲scope :red, -> { where(color: 'red') }。在前一種使用中有很多缺陷,並且它使得實現 更加複雜和錯誤。 (如果您願意,您可以定義一個名爲self.red的類方法 。)。