6

我在使用关联时遇到了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_byhas_many through协会合作。

4

1 回答 1

1

它有效,但不适用于:through.

于 2010-02-09T21:50:22.580 回答