Using parameters in my controller
So I'm using the excellent Ancestry gem But while the documentation seems very complete I don't understand how to pass the parameter of my element which I want to be the parent of my newly created element. Firstly, do I want to do it in the new
or create
action... allow me to explain. For example: (with some actions removed for brevity)
class PeopleController < ApplicationController
#...
def new
@person = Person.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Registration Successful."
redirect_to root_url
else
render :action => 'new'
end
end
end
So namely I don't know where to create the ancestry, the docs say:
...You can use the parent attribute to organise your records into a tree. If you have the id of the record you want to use as a parent and don’t want to fetch it, you can also use
parent_id
. Like any virtual model attributes,parent
andparent_id
can be set usingparent=
andparent_id=
on a record or by including them in the hash passed tonew
,create
,create!
,update_attributes
andupdate_attributes!
. For example:
TreeNode.create! :name => 'Stinky', :parent => TreeNode.create!(:name => 'Squeeky')
I want to know what my controller show look like to allow me to set the parent of the @person when I create them.
So otherwise I'm stuck, I don't know what else to do here... but anyhow, I do know that this gem is similar to the more popular acts_as_tree
, any help is super appreciated!
Updated
I think I almost have it but when I try this for my create action
def create
@parent = Recipe.find(params[:parent])
@recipe = Recipe.new(params[:recipe], :parent => @parent.id) do |recipe|
recipe.user_id = current_user.id
end
if @recipe.save
current_user.has_role!(:owner, @recipe)
redirect_to @recipe
else
render :action => 'new'
end
end
I get:
Couldn't find Recipe without an ID
Updated
My view h开发者_运维百科as a link to the new
action that looks like this <%= link_to "fork this recipe", {:controller => "recipes", :action => "new", :parent => @recipe} %>
That seems to look fine to me, also the url reads fine when you get to the form, recipes/new?parent=112
, but I still get that error, there has to be a way for that parameter to be passed as the parent of the newly created object.
If it works like acts_as_tree
then I'll assume that you can do something like this:
@parent.children.create(attributes)
Which will create a new child object with the parent set, regardless of what the attributes say.
According to the docs that you pasted you can do:
#...
@user = User.new(params[:user])
@user.parent_id = @parent_user.id
@user.save
#...
You can also include it in the params hash for the user -- your form submission would need to have params[:user][:parent_id]:
@user = User.create(params[:user])
精彩评论