0

currently in my update controller method I have:

@group.attributes = {
  :title => params[:group][:title],
  :description => params[:group][:description],
  :password_required => params[:group][:password_required],
  :password => params[:group][:password],
  :archived => params[:group][:archived]
}

The problem is that this method is used in multiple places and all of these params are not always passed which results in a "nil" which causes the db commit to rollback.

How can you set attributes only when they are defined w/o having to use if blocks?

Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

2 Answers2

3

Could probably do something lousy like this:

@group.attributes = {
  :title => params[:group][:title] || @group.title,
  :description => params[:group][:description] || @group.description,
  :password_required => params[:group][:password_required] || @group.password_required,
  :password => params[:group][:password] || @group.password,
  :archived => params[:group][:archived] || @group.archived
}

This kind of ugly code is not recommended, but it answers the question of how to do this without explicit if blocks.

Larsenal
  • 49,878
  • 43
  • 152
  • 220
2

why not simplify it with

@group.update_attributes(params[:group])

this way if the value us nil it wont be updated

Yuriy Goldshtrakh
  • 2,014
  • 1
  • 11
  • 7
  • That code saves the group, if you want to do some more processing before saving, you could do: @group.attributes = params[:group] # more code here... group.save In fact, the update_attributes method is basically those two lines... – iwiznia Jun 28 '12 at 17:53