wizztjh
wizztjh

Reputation: 7041

Bulk update has_many relationship model from belongs_to model

class Project < ActiveRecord::Base
  has_many :pages
  attr_accessible :name, :class_name, :content, :style

  def bulk_update_pages(attributes)
    for a in attributes do
      pages.find(a['id'].to_i).update_attributes(a) if pages.exists?(a['id'])
    end
  end

end

class Page < ActiveRecord::Base
  belongs_to :project
end

Is it a good way to bulk update pages from project ? Project.find(session[:ProjectId]).bulk_update_pages(params)

Upvotes: 1

Views: 4414

Answers (2)

Tobias Cohen
Tobias Cohen

Reputation: 20000

I think you'd be better off using a nested form:
http://railscasts.com/episodes/196-nested-model-form-part-1

Upvotes: 1

wael34218
wael34218

Reputation: 4930

Try setting the association to
has_many :pages, :autosave => true

"If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object" Rails guide 4.1.2

http://guides.rubyonrails.org/association_basics.html

Upvotes: 1

Related Questions