[英]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 view 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 当我查看Thing时,我想提供一个指向新事物页面的链接,以创建一个parent_id填充有当前Thing的ID的子对象,所以我想我会使用它
<%= 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 但这不起作用,因为默认操作是对控制器中的GET方法进行操作,该方法无法在具有以下参数的params中找到:id
@thing = Thing.find(params[:id])
so the question is; 所以问题是
a) should I have a new controller for children or; a)我应该为孩子配备一个新的控制器吗?
b) is there a better way to send the param of the parent_id through to the GET method in the Thing controller b)是否有更好的方法将Thing控制器中的parent_id参数发送到GET方法
Thanks in advance 提前致谢
Heath. 希思。
You don't have to create a new Controller for this purpose. 为此,您不必创建新的Controller。 You could also do it with some additional routes and actions in your existing Controller.
您还可以通过现有Controller中的一些其他路由和操作来完成此操作。 If you already have a Thing controller mapped as a resource, you could add additional routes like this:
如果您已经将Thing控制器映射为资源,则可以添加其他路由,如下所示:
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)
在新动作中:
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! 我想我真正的问题应该是如何在Rails的GET中添加参数!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.