5
我在has_many
through
关联中使用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_many
through
协会。
是的,问题局限于:通过。我会更新这个问题来反映这一点。 – 2010-02-09 22:13:00
我不认为你会得到任何更多的答案在这一个。 'find_or _...'方法不应该与':through'关联一起工作。 您可以通过删除'Permission'模型并使用'has_and_belongs_to_many'关系和一个简单的映射表来实现它的唯一方法。 – 2010-02-09 22:18:39
调用'u.roles.find_by_rolename(“admin”)''与'has_many:through'配合使用。所以我想'u.roles.find_or_create_by_rolename(“admin”)'可能会工作。你能指点我指定这个警告的文档吗? – 2010-02-09 22:33:00