1

So, this:

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

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

works as expected, saving the person's name. But, how would I do this:

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

I can't figure out the right projection to get the organization fields to map (or if it's possible). I've tried '*' and 'organization.name as "person.organization.name"'.

me_
  • 13
  • 2

2 Answers2

1

In order for what you're doing to work, you have to set the autosave option to true in your belongs_to :organization association.

belongs_to :organization, autosave: true

or just call save on the organization

p.organization.name = 'Org Name'
p.organization.save
jvnill
  • 29,479
  • 4
  • 83
  • 86
0

You have to declare association in your Person class, using belongs_to has_one has_many has_many :through has_one :through or has_and_belongs_to_many, and Rails will do the join by it self and link your both class together.

Let me paste here a section of Rails guide:

With Active Record associations, we can [..] tell Rails that there is a connection between the two models. Here’s the revised code for setting up customers and orders:

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

class Order < ActiveRecord::Base
  belongs_to :customer
end

With this change, creating a new order for a particular customer is easier:

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

I suggest you read the complete guide here: http://guides.rubyonrails.org/association_basics.html

Benjamin Bouchet
  • 12,971
  • 2
  • 41
  • 73
  • No, you misunderstand, I'm talking about this situation: http://stackoverflow.com/a/639844/2130025 – me_ Mar 04 '13 at 01:27