【问题标题】:Rails HABTM association: record not inserting into joining tableRails HABTM 关联:记录未插入连接表
【发布时间】:2013-08-14 12:28:38
【问题描述】:

我必须为UserCompany 建模。 以及像这样的关联:

class User < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

class Company < ActiveRecord::Base
  has_and_belongs_to_many :users
end

在迁移中创建连接表:

class CreateCompaniesUsers < ActiveRecord::Migration
 def change
   create_table :companies_users, :id => false do |t|
     t.references :company
     t.references :user

     t.timestamps
   end
 end
end

工作正常,当:

user = User.new(:name => "name", :email => "email@em.com" :password => "pass")
user.companies.find_or_create_by_name(:name => "name")

user.save

它不工作,(但将数据插入userscompanies)时:

user = User.first # or by finding some existing user
user.companies.find_or_create_by_name(:name => "name")

此外,它还显示一条消息:

Creating scope :page. Overwriting existing method Company.page.

请帮助我摆脱困境。谢谢。

【问题讨论】:

  • 也许你用错了方法,试试user.companies.find_or_create_by(:name =&gt; "name"),你想找到/创建属于用户名为name的新公司吗?

标签: ruby-on-rails-3 associations


【解决方案1】:

您是否使用 Kaminari 进行分页?请看本期:https://github.com/amatsuda/kaminari/issues/48

多年来,有许多针对 Kaminari 的此类问题,包括一个基于同时使用 will_paginate 的问题。所有这些问题都会导致您看到“创建范围:页面”消息。

尝试从您的 gemfile/bundle 中删除 Kaminari,然后重试您的测试用例。

或者,尝试检查您在 user.companies 中创建的新公司并确保它有效。如果新创建的对象未通过验证,则 find_or_create 将不会保存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多