Ruby on Rails - 由于关联而缺少属性错误

时间:2015-08-21 18:25:13

标签: ruby-on-rails ruby ruby-on-rails-4 foreign-keys foreign-key-relationship

我有两个模特。

  • 公司
  • 备忘录

我希望公司有多份备忘录和备忘录,只有一家公司。

memorandum.rb

class Memorandum < ActiveRecord::Base
  belongs_to :company
end

company.rb

class Company < ActiveRecord::Base
  has_many :memorandums, dependent: :destroy
  # validation lines omitted
end

当我尝试将外键分配给备忘录时,我收到遗漏属性错误can't write unknown attribute "company_id"

我在公司控制器内部分配公司。备忘录是在此之前创建的,当前备忘录的ID保存在会话哈希中。

companies_controller.rb

def create
  @company = Company.new(company_params)
  Memorandum.find(session[:memorandum_id]).company = @company

  respond_to do |format|
    if @company.save
      format.html { redirect_to @company, notice: 'Company was successfully created.' }
      format.json { render action: 'show', status: :created, location: @company }
    else
      format.html { render action: 'new' }
      format.json { render json: @company.errors, status: :unprocessable_entity }
    end
  end
end

1 个答案:

答案 0 :(得分:0)

我强烈建议你阅读Active Record Association.的Ruby on Rails指南。这里有非常清楚地解释概念。

以下是两个示例链接:has_manybelongs_to,可以帮助您理解。

要解决当前问题,您需要迁移才能将memorandums添加到rails g migration addCompanyIdToMemorandums company_id:integer 表中:

bundle exec rake db:migrate

然后运行迁移:

company

正如上面的指南所解释的那样,你需要在belongs_to关联表中指定一个外键来指向它的父表。至于您的备忘录belongs_to company_id,因此您必须在备忘录表格中添加Collections.sort(list, new Comparator<CustomObject>() { @Override public int compare(final CustomObject object1, final CustomObject object2) { return object1.v1 > object2.v1? -1 : object1.v1 < object2.v1 ? +1 : 0; } }); ,我们刚刚使用上述迁移进行了此操作。