Search code examples
ruby-on-railsmass-assignment

Rails parent child form example preventing mass assignment


I use rails 3.2 and I want to prevent mass-assignment. I have parent-child relationship.

class Parent < ActiveRecord:Base
    has_many :children
    attr_accessible :name
end
class Child < ActiveRecord:Base
    belongs_to :parent
    attr_accessible :title
end

In my routes.rb child resource is not nested within parent resource. Now I have a link to create a new child with new_child_path(@parent.id). This directs me to localhost:3000/child/new?parent_id=1 and I end up in new action:

def new
    @child = Child.new
    @parent = Parent.find(params[:parent_id])
    @child.parent = @parent
end

My question is: how to write my _form.html.erb for a child entity? I cannot use f.hidden_field for parent_id because in my create action it would break up because of mass-assignment. On the other hand I need to pass parent_id to know my parent when I save child. I haven't found a good working example for this.


Solution

  • You should read up on Rails' nested resources.

    Some links:

    http://railscasts.com/episodes/139-nested-resources

    -- EDIT 1 --

    Based on your comment of not having more than one level of nesting, you could also have the following route configuration:

    resources :grandparents do
        resources :parents
    end
    
    resources :parents do
        resources :children
    end
    

    This way, you can still have the parent child relationship, without the overheads of multiple levels of nesting. You could also namespace your controllers to keep things clean, eg:

    resources :grandparents do
        resources :parents, :controller => "grandparent/parent"
    end
    
    resources :parents do
        resources :children
    end