0

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.

Tomasz Kalkosiński
  • 3,673
  • 1
  • 19
  • 25

1 Answers1

1

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
zsquare
  • 9,916
  • 6
  • 53
  • 87
  • I did read http://guides.rubyonrails.org/routing.html#nested-resources but I've followed a rule: Resources should never be nested more than 1 level deep, so I dropped my nested resources. – Tomasz Kalkosiński May 30 '12 at 12:20
  • This solves an issue of having parent_id in my URL while creating a book. Too bad this routes practice is not widely popular. Thank you. – Tomasz Kalkosiński May 30 '12 at 12:38