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

标签 ruby-on-rails activerecord has-many

我在使用 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/

相关文章:

ruby-on-rails - rails 3.1 : How can I stop the view from displaying the array along with the data for 2 associated models?

json - 使用 sequelize 防止将连接表数据添加到 json

ruby-on-rails - rails 以茧的形式嵌套。使用模型的属性

ruby-on-rails - 'Travel' 时间助手是否在功能规范中不可用?

ruby-on-rails - Rails、Postgres 和时区

ruby-on-rails - 使用边缘生成 Rails 应用程序的最佳方法是什么?

ruby-on-rails - 路由错误 - 没有新的路由与 [POST] 匹配

ruby - ActiveRecord迁移:unique => true being ignored?

mysql - 与 Rails 一起迷失 has_many : through multiple search

mysql - 为什么 activerecord 不填充从创建返回的项目中的自动递增列?