【问题标题】:Rails Active Record: modifying and saving the child of an object from the result of joins?Rails Active Record:从连接结果中修改和保存对象的子对象?
【发布时间】:2013-02-18 00:09:59
【问题描述】:

所以,这个:

p = Person
.joins('join organization o on o.id = organization_id')
.where('o.id' => 1)
.select('person.*')
.first!

p.name = 'hi!'
p.save!

按预期工作,保存此人的姓名。 但是,我该怎么做:

p.organization.name = 'bye!'
p.save!

我无法找出正确的投影来映射组织字段(或者如果可能的话)。我试过 '*' 和 'organization.name as "person.organization.name"'。

【问题讨论】:

    标签: ruby-on-rails activerecord join rails-activerecord arel


    【解决方案1】:

    为了使您所做的工作正常工作,您必须在您的 belongs_to :organization 关联中将 autosave 选项设置为 true。

    belongs_to :organization, autosave: true
    

    或者只是在组织上调用 save

    p.organization.name = 'Org Name'
    p.organization.save
    

    【讨论】:

    • 谢谢,这就是我所缺少的。
    【解决方案2】:

    你必须在你的 Person 类中声明关联,使用 属于 has_one 有很多 has_many:通过 has_one :通过 或 has_and_belongs_to_many, Rails 将自己进行连接并将您的两个类链接在一起。

    让我在这里粘贴一段 Rails 指南:

    通过 Active Record 关联,我们可以 [..] 告诉 Rails 这两个模型之间存在联系。这是用于设置客户和订单的修改后的代码:

    class Customer < ActiveRecord::Base
      has_many :orders, :dependent => :destroy
    end
    
    class Order < ActiveRecord::Base
      belongs_to :customer
    end
    

    通过此更改,为特定客户创建新订单变得更加容易:

    @order = @customer.orders.create(:order_date => Time.now)
    

    我建议您在这里阅读完整指南:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多