【问题标题】:Error while using `find_or_create_by` on a `has_many` `through` association在 `has_many` `through` 关联上使用 `find_or_create_by` 时出错
【发布时间】:2010-02-09 21:36:06
【问题描述】:

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

当我在 rolesUser 对象的关联上调用 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 关联一起使用。

【问题讨论】:

    标签: ruby-on-rails activerecord has-many


    【解决方案1】:

    它有效,但不适用于:through

    【讨论】:

    • 是的,问题仅限于 :through。我将更新问题以反映这一点。
    • 我不认为你会在这个问题上得到更多答案。 find_or_... 方法不应该与 :through 关联一起使用。让它工作的唯一方法是删除Permission 模型并使用has_and_belongs_to_many 关系和一个简单的映射表。
    • u.roles.find_by_rolename("admin") 等调用与has_many :through 一起使用。所以我认为u.roles.find_or_create_by_rolename("admin") 可能会起作用。您能否指出指定此警告的文档?
    • 我很乐意证明这个问题,但是 find_by-methods 没有很好地记录。但是我认为很容易理解为什么“创建”部分不起作用(而“查找”部分起作用):创建需要猜测/生成映射“权限”。 Rails 可以用habtm 做到这一点,但不能用复杂的类型(如果你在权限中有验证器怎么办?你会被搞砸的。)
    • u.roles.create(:rolename =&gt; "admin") 这样的create 调用有效。 Rails 自动创建Permission 映射。我希望find_or_create 能够类似地工作(假设没有验证错误)。在这个阶段,我很想知道这是有意识的遗漏还是错误。
    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多