tokhi
tokhi

Reputation: 21616

ActiveRecord relationship practice

I have below models:

class Foo < ActiveRecord::Base
  attr_accessible :name, headline
end

~

class Unit < ActiveRecord::Base
  attr_accessible :title, :bar
  has_many :sites
  has_many :articles, :through => :sites
  belongs_to :foo
end

~

class Site < ActiveRecord::Base
  attr_accessible :article_id
  belongs_to :unit
  belongs_to :article
end

~

class Article < ActiveRecord::Base
  attr_accessible :title
  has_many :sites
  has_many :units, :through => :sites
end

Now on foos_controller I get foo's units:

class FoosController < ApplicationController
  #...
  units = Unit.where(:foo_id => params[:foo_id])
  # Now here I want to set each unit title with its site.article.title
end

how can I set the unit.title with its site.article.title?

Upvotes: 0

Views: 55

Answers (2)

PinnyM
PinnyM

Reputation: 35531

Based on your description, it appears that a Unit has one Site - so you need to add that association:

class Unit < ActiveRecord::Base
  attr_accessible :title, :foo
  has_one :site
  belongs_to :foo
end

Now you can do this:

units = Unit.where(:foo_id => params[:foo_id]).includes(:articles)
units.each do |unit| 
   unit.update_attributes(title: unit.articles.first.title)
end

Note the use of includes in the original query. This will eager load the articles necessary to avoid an N+1 query problem when you iterate through the units.

Note that this approach assumes you don't have very many articles per unit. If you did, this would need to be tweaked to avoid loading too many articles unnecessarily.

Upvotes: 1

elreimundo
elreimundo

Reputation: 6276

It looks like a Site should also belongs_to :article based on the syntax you're using and based on the fact that it has an article_id. You can remove attr_accessible :article_id unless you explicitly want that to change and instead add belongs_to :article. You'll then be able to call unit.title = site.article.title (or you could use unit.update_attribute('title',site.article.title)

Upvotes: 0

Related Questions