2010-02-09 74 views
5

我在has_manythrough关联中使用find_or_create_by时遇到了问题。当我roles相关联的User对象的调用find_or_create_by通过`has_many```通过`关联使用`find_or_create_by`时出错

class Permission < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :role 
end 

class Role < ActiveRecord::Base 
    # DB columns: user_id, role_id 

    has_many :permissions 
    has_many :users, :through => :permissions 
end 

class User 
    has_many :permissions 
    has_many :roles, :through => :permissions 
end 

滑轨引发错误。

u = User.first 
u.roles.find_or_create_by_rolename("admin") 

# Rails throws the following error 
# NoMethodError: undefined method `user_id=' for #<Role id: nil, rolename: nil, 
# created_at: nil, updated_at: nil> 

我能够改变我的代码来解决如下问题:

unless u.roles.exists?(:rolename => "admin") 
    u.roles << Role.find_or_create_by_rolename("admin") 
end 

我好奇地发现,如果find_or_create_by作品与has_manythrough协会。

回答

1

它的工作原理,但不适用于:through

+0

是的,问题局限于:通过。我会更新这个问题来反映这一点。 – 2010-02-09 22:13:00

+0

我不认为你会得到任何更多的答案在这一个。 'find_or _...'方法不应该与':through'关联一起工作。 您可以通过删除'Permission'模型并使用'has_and_belongs_to_many'关系和一个简单的映射表来实现它的唯一方法。 – 2010-02-09 22:18:39

+0

调用'u.roles.find_by_rolename(“admin”)''与'has_many:through'配合使用。所以我想'u.roles.find_or_create_by_rolename(“admin”)'可能会工作。你能指点我指定这个警告的文档吗? – 2010-02-09 22:33:00