在`has_many``到`关联上使用`find_or_create_by`时出错

Har*_*tty 6 activerecord ruby-on-rails has-many

我同时使用运行在一个问题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
Run Code Online (Sandbox Code Playgroud)

当调用的Rails引发错误find_or_create_byroles一个关联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>
Run Code Online (Sandbox Code Playgroud)

我能够通过更改我的代码来解决此问题,如下所示:

unless u.roles.exists?(:rolename => "admin")
  u.roles << Role.find_or_create_by_rolename("admin") 
end
Run Code Online (Sandbox Code Playgroud)

我很想知道是否find_or_create_byhas_many through协会合作.

Mar*_*rth 1

它可以工作,但不能与:through.