Link_to remote => true causing strange routing problems, Rails 3

冷暖自知 提交于 2019-12-11 19:58:56

问题


I am having some problems with link_to remote sending a post to another controller... The result are not quite what I expect..

I have this in node_content.html.erb:

<% @node.videos.each do |vid| %>
 <div id="vid_vid"><%= link_to image_tag("http://img.youtube.com/vi/#{vid.content}/1.jpg"),  :controller => 'videos', :action => "iframize", :video_id => vid.id,  :method => :post,  :remote => true %></div>

 <% end %>

And I have this in videos_controller:

  def iframize
   @video = Video.find(params[:video_id])
   respond_to do |format|
     format.js
   end
 end

And this in routes:

 resource :videos do
  collection do
   post 'iframize'
  end
end

Problem is that when I click the link, it takes me to

http://localhost:3000/videos/iframize?method=post&video_id=20

and I get

Couldn't find Video with id=iframize

I looked through tens of various examples and they seem to recommend the above, but it does not work.. What am I doing wrong?

Any input greatly appreciated!

Thanks!

EDIT:

I tried this approach jquery function and it kinda worked (only for the first video in the loop of course):

<% @node.videos.each do |vid| %>
  <%=  image_tag("http://img.youtube.com/vi/#{vid.content}/1.jpg", :id  => 'img_div') %>
<div id="vid_vid"> <%= vid.id %></div>
<% end %>



$('#img_div').on({
  'click': function() {
   var vid_id = document.getElementById("vid_vid").innerHTML;
   $.post("/videos/iframize/", {video_id: vid_id}); 
  }
 });

回答1:


Do you have rails_ujs included via jquery_ujs in assets/application.css file

= link_to image_tag("http://img.youtube.com/vi/#{vid.content}/1.jpg"), "url_path", :method => :post,  :remote => true

Convert the following into a rails path: like iframeize_videos_path (generated via rake routes)

:controller => 'videos', :action => "iframize", :video_id => vid.id,



回答2:


You need to differentiate the url options, html options.so use

<%= link_to image_tag("http://img.youtube.com/vi/#{vid.content}/1.jpg"), 
{ :controller => 'videos', :action => "iframize", :video_id => vid.id },
{ :method => :post,  :remote => true} %>


来源:https://stackoverflow.com/questions/9971879/link-to-remote-true-causing-strange-routing-problems-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!