ScottOBot
ScottOBot

Reputation: 849

Ruby on Rails - Accessing Parent Attribute Though One to Many Association

I'm fairly new to Ruby on Rails and am having issues using a one to many association I set up between two models. Here is the code for the two models that define the one to many association:

class Location < ActiveRecord::Base
  has_many :reviews, -> { order 'created_at DESC' }, dependent: :destroy
  has_many :share_locations, dependent: :destroy
end

class ShareLocation < ActiveRecord::Base
  belongs_to :location
end

In a view controller I find a ShareLocation instance and attempt to change an attribute of the Location it belongs to.

@share_location = ShareLocation.find_by(share_code: share_code)

if @share_location
  @share_location.is_valid = false
  @share_location.location.owner_id = new_owner_id
  @share_location.save
end

When I change the is_valid attribute of the ShareLocation instance it properly updates upon save. However when I attempt to update the owner_id of the Location that the ShareLocation belongs to nothing seems to happen. I am pretty new at this and hope this question hasn't already been asked/answered. I did some research and found many questions that mentioned nested attributes and :foreign_key. I can't seem to grasp these concepts and am having trouble seeing how they could help or be applied to my situation. Could someone please explain to me how to solve this issue and what exactly I am doing wrong. If this question is a repeat please point me in the right direction and I will remove it.

Upvotes: 0

Views: 102

Answers (2)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

The issue with your code is that you're updating 2 objects: share_location AND location, but saving only share_location. To save both objects, you can:

if @share_location
  @share_location.is_valid = false
  @share_location.save

  @share_location.location.owner_id = new_owner_id
  @share_location.location.save
end

OR if you want to save associated models automatically, you could use :autosave option on your association:

AutosaveAssociation is a module that takes care of automatically saving associated records when their parent is saved.

I didn't try, but it should work with belongs_to:

class ShareLocation < ActiveRecord::Base
  belongs_to :location, autosave: true
end

Having this, you should be able to save parent(share_location) and Rails will take care of saving associated location automatically.

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

What you need is autosave, I thought it should be working but I just looked this up

When the :autosave option is not present then new association records are saved but the updated association records are not saved

So this is why your update isn't saved, to fix this you need to force autosave

class Location < ActiveRecord::Base
  has_many :share_locations, dependent: :destroy, autosave: true
end

Upvotes: 0

Related Questions