August 12, 2009

fields_for in Rails, but no one mentions it (part 2)

Just an addition to my previous post on using fields_for.

A second approach to the same issue of working with the params data would be to utilize the attr_accessible method in the model.

1
2
3
class Page < ActiveRecord::Base
  attr_accessible :name
end

Using attr_accessible indicates what values of the model can be mass assigned. That I’ve only set :name, no attempt will be made to write the content portion of params. You can simply do the following:

1
2
3
4
5
6
7
@page = Page.new(params[:page]) # create the page
content = @page.contents.build(params[:page][:page][:content]) # create the content

if @page.valid? and content.valid?
  @page.save
  content.save
end

Both approaches work, but this will keep the controller clean.

Leave a Comment


Please wait...