【问题标题】:Ruby on Rails multiple belongs_to associations savingRuby on Rails 多个 belongs_to 关联保存
【发布时间】:2012-09-12 15:43:08
【问题描述】:

Rails 的belongs_to 概念中有些东西我不太理解。文档状态:

Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object

假设我有一个Employee 实体:

class Employee < ActiveRecord::Base  
  belongs_to :department
  belongs_to :city    
  belongs_to :pay_grade
end

以下代码会触发三个更新吗?如果是,有更好的方法吗? :

e = Employee.create("John Smith")
Department.find(1) << e
City.find(42) << e
Pay_Grade.find("P-78") << e

【问题讨论】:

    标签: ruby-on-rails activerecord associations belongs-to


    【解决方案1】:

    您可以简单地分配它:

    e = Employee.new(:name => "John Smith")
    e.department = Department.find(1)
    e.city = City.find(42)
    e.pay_grade = Pay_Grade.where(:name => "P-78")
    
    e.save
    

    我将 create 更改为 new 以在保存之前构造对象。构造函数采用散列,而不是不同的值。 find 只接受 id 而不是字符串,而是在字段上使用 where

    您还可以使用以下内容:

    Employee.create(:name => "John Smith", 
                    :department => Department.find(1), 
                    :city => City.find(42), 
                    :pay_grade => PayGrade.where(:name => "P-78").first
    

    另请注意,型号名称应为驼峰式:PayGrade 而不是 Pay_Grade

    【讨论】:

    • 好的,但是如果我使用 departement.employees 表格会发生什么? RoR 会等到最后一个 collection# 操作再保存还是会每次触发一个更新语句?
    • &lt;&lt; 立即写入数据库。
    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    相关资源
    最近更新 更多