Error while using `find_or_create_by` on a `has_many` `through` association

两盒软妹~` 提交于 2019-12-06 01:52:29

问题


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 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>

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

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


回答1:


It works, but not with :through.



来源:https://stackoverflow.com/questions/2232705/error-while-using-find-or-create-by-on-a-has-many-through-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!