开发者

Adding a new record with a self join in Rails

I have a self join on an object "thing"

class Thing < ActiveRecord::Base  
    has_many :children, :class_name => "Thing", :foreign_key => "parent_id"  
    belongs_to :parent, :class_name => "Thing"    
end

When I vi开发者_StackOverflow社区ew a Thing I want to provide a link to the new thing page to create a child object with the parent_id populated with the id of the current Thing, so I thought I would use this

<%= link_to 'New child thing', new_thing_path(@thing) %>

but that doesn't work as the default action is to the GET method in the controller which can't find the :id in the params with

@thing = Thing.find(params[:id])

so the question is;

a) should I have a new controller for children or;

b) is there a better way to send the param of the parent_id through to the GET method in the Thing controller

Thanks in advance

Heath.


You don't have to create a new Controller for this purpose. You could also do it with some additional routes and actions in your existing Controller. If you already have a Thing controller mapped as a resource, you could add additional routes like this:

map.resources :things, :member => { :new_child => :get, :create_child => :post }

which will give you two additional routes:

new_child_thing     GET   /things/:id/new_child(.:format)
create_child_thing  POST  /things/:id/create_child(.:format)

Then you can add those two actions to your controller and handle the creation in them

def new_child
  @parent_thing = Thing.find(params[:thing_id])
  @thing = Thing.new
  ...
end

def create_child
  @parent_thing = Thing.find(params[:thing_id])
  @thing = Thing.new(params[:thing])
  @thing.parent = @parent_thing
  if @thing.save
    render :action => :show
  else
    render :action => :new_child
  end
end


new_thing_path(:parent_id => @thing.id)

And in the new action:

parent = Thing.find params[:parent_id]


<%= link_to 'New linked thing', new_thing_path(:Parent_id=>@thing.id) %>

and in the controller

def new
    @parent = Thing.find(params[:Parent_id])
    @thing = Thing.new
    @thing.parent_id = @parent.id
    respond_to do |format|
       format.html # new.html.erb
       format.xml  { render :xml => @organizr }
    end
 end

I guess my real question should have been how do I add parameters to a GET in Rails!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜