我在使用 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
时 Rails 抛出错误在 roles
协会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_by
与 has_many
合作through
协会。
最佳答案
它有效,但不适用于 :through
.
关于ruby-on-rails - 在 `find_or_create_by` `has_many` 关联上使用 `through` 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2232705/