我认为我是一个记录的实例。它有很多通过记录属于用户和帐户。我有这个实例,我试图找到属于它的用户。这似乎很简单,因为我在此实例上具有user_id权限。但是,当我调用membership.user时,它返回一个未定义的方法错误?我真的无法想象这一点。这是我的代码:
def owner
owner = current_account.account_memberships.where(admin: true)
end
这将返回此记录:
[#<AccountMembership:0x007fabf7cf9978
id: 1,
user_id: 1,
account_id: 1,
admin: true,
worker: false,
created_at: Sun, 22 Jan 2017 04:25:37 UTC +00:00,
updated_at: Sun, 22 Jan 2017 04:25:37 UTC +00:00>]
如果我调用此owner.id
,我会收到此错误:
NoMethodError: undefined method `id' for #<AccountMembership::ActiveRecord_AssociationRelation:0x007fabfcc0c1f0>
你的意思是? IDS
以下是模型:
has_many :account_memberships
has_many :accounts, through: :account_memberships
has_many :account_memberships
has_many :users, through: :account_memberships
belongs_to :account
belongs_to :user
我做错了什么我不知道是什么。谢谢你的帮助!
答案 0 :(得分:1)
def owner
owner = current_account.account_memberships.where(admin: true)
end
在上面的方法中,owner是ActiveRelation。您需要致电first
才能获得实际订单。您还可以通过调用to_a
current_account.account_memberships.where(admin: true).first.id