开发者

Destroy? Delete? What's going on here? Rails 2.3.5

开发者 https://www.devze.com 2022-12-21 23:53 出处:网络
I am new to rails. My rails version is 2.3.5. I found usage like: In controller, a destroy method is defined and in view, you can use :action => \"delete\" to fire that method. Isn\'t the action name

I am new to rails. My rails version is 2.3.5. I found usage like:

In controller, a destroy method is defined and in view, you can use :action => "delete" to fire that method. Isn't the action name has to be the same as the method name? Why delete is mapped to destroy?

Again, in my controller, I define a method called destroy to delete a record. In a view, I have <%= link_to "remove", :action => 'destroy', :id => myrecord %>. But it never works in practice. Every time I press the remove link, 开发者_JAVA技巧it redirects me to the show view, showing the record's content. I am pretty sure that my destroy method is:

def destroy
    @myobject = MyObject.find(params[:id])
    @myobject.destroy
    @redirect_to :action = 'index'
end

If I change the method name from destroy to something like remove_me and change the action name to remove_me in the view, everything works as expected.

In the above two weird problems, I am sure there is no tricky routing set in my configuration.

All in all, seems the destroy and delete are mysterious keywords in rails. Can anyone explain this to me?


You probably set MyObject as a resource in routes.rb. Resources get a couple of routes that don't directly match the name of the action. When you use an action name that does not match the routes defined by the resource, you'll get the default route which directly maps to the name of the action.

I found that this link explains rails' routing very well. Take a look at the "RESTful routing" section.


If you are using REST routing, destory only support delete method. you can change your code like this

 link_to "remove", :action => 'destroy', :id => myrecord", :method => :delete

Adding :method => :delete rails will add a hidden input with name "_method", value "delete"


Replace all :post => true with :method => :post

0

精彩评论

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