【发布时间】:2010-02-09 21:36:06
【问题描述】:
我在 has_many through 关联上使用 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
当我在 roles 与 User 对象的关联上调用 find_or_create_by 时,Rails 会引发错误。
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 关联一起使用。
【问题讨论】:
标签: ruby-on-rails activerecord has-many