在“has_many”“through”关联上使用“find_or_create_by”时出错
我在 has_many
through
关联上使用 find_or_create_by
时遇到问题。
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
当我对 User
对象的 roles
关联调用 find_or_create_by
时,Rails 会引发错误。
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
关联一起使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以工作,但不能与
:through
一起使用。It works, but not with
:through
.