2013-01-22 32 views
1

因此,試圖在我的user模型中編寫scope,我似乎無法讓它工作。使用lambda導軌3範圍關聯錯誤

user模型看起來有幾分像這樣

class User < ActiveRecord::Base 
    has_one :user_profile 

    scope :api_user, lambda { |member_code| joins(:users, user_profiles).where('user_profiles.member_code = ?', member_code)} 

而且我user_profiles模式是這樣的:

class UserProfile < ActiveRecord::Base 
    belongs_to :user 

當我打電話scope在軌道控制檯,像這樣:

User.api_user(4321) 

我收到此錯誤:

ActiveRecord::ConfigurationError: Association named 'users' was not found; perhaps you misspelled it? 

我是新來的作用域,我知道如何做到這一點,沒有他們,如果我這樣做:

User.find_by_id(UserProfile.find_by_member_code(4321).user_id) 

它返回正是我想要的。但我將需要多次使用它(編寫一個api),所以我真的很想讓scope工作。

已經查看了這些問題herehere,但他們沒有說明我的問題。

回答

2

joins只需要列出關聯,而不是自己。所以它應該看起來像這樣:

scope :api_user, lambda { |member_code| joins(:user_profile).where('user_profiles.member_code = ?', member_code) } 
+0

謝謝,那有效。 – Ryan