Using accepts_nested_attributes_for + mass assignment protection in Rails

Say you have this structure:

class House < ActiveRecord::Base has_many :rooms accepts_nested_attributes_for :rooms attr_accessible :rooms_attributes end class Room < ActiveRecord::Base has_one :tv accepts_nested_attributes_for :tv attr_accessible :tv_attributes end class Tv belongs_to :user attr_accessible :manufacturer validates_presence_of :user end 

Please note that the Tv user is not available for its intended purpose. Thus, you have a triple nested form that allows you to enter the house, rooms and televisions on one page.

Here the controller creates the method:

 def create @house = House.new(params[:house]) if @house.save # ... standard stuff else # ... standard stuff end end 

Question: How in the world would you fill in user_id for each tv (it should come from current_user.id)? What is good practice?

Here is catch2, I see this.

  • Configure user_ids directly in the params hash (they are pretty deeply nested)
    • Save fails because user_ids not assigned to the mass
  • Fills user for each TV after #save is completed
    • Will not save, because user_id must be present
    • Even if we get by, tvs will be without identifiers for some time - sucks

Any decent way to do this?

+6
ruby ruby-on-rails nested-forms mass-assignment
source share
1 answer

Is there something wrong with this?

 def create @house = House.new(params[:house]) @house.rooms.map {|room| room.tv }.each {|tv| tv.user = current_user } if @house.save # ... standard stuff else # ... standard stuff end end 

I have not tried this, but it seems that the objects should be built and accessible at this stage, even if they are not saved.

+2
source share

All Articles