Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

Simple routing in Rails

I'm trying to destroy a link from a User Show view.

So from /users/1,

I want to access destroy action in teacher_student_links controller.

The first attempt:

<%= link_to 'destroy', :controller => "teacher_student_links", :action => "destroy", :id => @user.id %>

This fails because it routes to "show" action in the specified controller. So first question: why does it point to the "show" action instead of "destroy?" I tried to enclose the above with parenthesis, and got a meaningless error as well.

The second attempt:

in config/routes.rb

match '/bye_teacher' => 'teacher_student_links#destroy'

view

<%= link_to 'destroy', '/bye_teacher', :user_id => @user.id %>

also tried,

<%= link_to 'destroy', '/bye_teacher', :user_id => @user %>

Both lines correctly direct to the specified controller and action, but the parameter is not passed in. (can't find the user without an ID error)

second question: am I passing in the variable in a wrong way in this case?

It's little embarrassing to ask these two questions, but I wanted to know the reasons behind these problems.

UPDATE:

<%= link_to 'destroy', teacher_student_links_path(:user_id => @user), :method => :delete %>

gives

No route matches [DELETE] "/teacher_student_links"

<%= link_to 'destroy', teacher_student_links_path(@user), :method => :delete %>

gives

No route matches [DELETE] "/teacher_student_links.1"

... so I ran

rake routes and I got

DELETE /teacher_student_links/:id(.:format) teacher_student_links#destroy

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
match "/bye_teacher/:id" => "teacher_student_links#destroy"


<%= link_to 'destroy', teacher_student_links_path(:id), 
:confirm => 'Are you sure you want to destroy this teacher?', :method => :delete %>

This should also work in the view:

<%= link_to 'Destroy', :action => 'destroy', :id => @user.id, :method => :delete %>

Rails Routing from the Outside In


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...