本文介绍了同时采用`find_or_create_by`在``has_many`协会through`错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 find_or_create_by 的has_many 到的关联。

I am running in to a problem while using find_or_create_by on a has_many through association.

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

Rails的抛出当调用 find_or_create_by 角色错误用户对象。

Rails throws an error when I invoke find_or_create_by on roles association of a User object.

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>

我是能够解决的问题,通过改变我的code如下:

I was able to work around the problem by changing my code as follows:

unless u.roles.exists?(:rolename => "admin")
  u.roles << Role.find_or_create_by_rolename("admin") 
end

我好奇地发现,如果 find_or_create_by 适用于的has_many 的关联。

I am curious to find if find_or_create_by works with has_many through associations.

推荐答案

它的工作原理,但与:通过

这篇关于同时采用`find_or_create_by`在``has_many`协会through`错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 10:28