gpt4 book ai didi

ruby-on-rails - 在 `find_or_create_by` `has_many` 关联上使用 `through` 时出错

转载 作者:行者123 更新时间:2023-12-04 06:26:25 26 4
gpt4 key购买 nike

我在使用 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_byhas_many 合作 through协会。

最佳答案

它有效,但不适用于 :through .

关于ruby-on-rails - 在 `find_or_create_by` `has_many` 关联上使用 `through` 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2232705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com