我在使用关联时遇到了find_or_create_by
问题has_many
through
。
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
find_or_create_by
当我调用对象的roles
关联时, Rails 会引发错误User
。
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
协会合作。