2013-03-08 129 views
0

我的link_to是这样的:控制器和动作不执行控制器代码

<%= link_to image_tag(user_likes_selection.page_picture, :image_id =>  
user_likes_selection.id, :controller => :preferences_controller, 
:action => :checked_average_with_profile) %> 

我的控制器,preferences_controller,有一个名为checked_average_with_profile方法,其中,据我所知,是不是当我点击图片时被调用。

对从的link_to生成的HTML代码是

<img> 
<a href="/preferences"><img action="checked_average_with_profile" alt="Soul_surfer_film"  
controller="preferences_controller" height="70%" image_id="3254" 
src="/assets/soul_surfer_film.jpg" width="70%" /></a> 
</img> 

为什么单击图像时不执行的控制器编码?

回答

1

在这样的情况下,很容易,如果你使用的link_to

<%= link_to { :image_id => user_likes_selection.id, :controller => :preferences, :action => :checked_average_with_profile } do %> 
    <%= image_tag(user_likes_selection.page_picture %> 
<% end %> 
在你的路由

块形式阅读代码,还可以传递一个as选项所以你可以使用命名路线。假设你的路径看起来像

match '/preferences/checked_average_with_profile/:image_id' => 'preferences#checked_average_with_profile', as: :check_average_profile 

您可以使用

link_to image_tag(user_likes_selection.page_picture), check_average_profile_path(user_likes_selection.id) 
+0

这看起来应该可行,但出于某种原因,当图像被点击时,我的应用程序重定向到root_url而不是preferences_url。另外,我的控制器指定的数据都没有输入到数据库中。有什么建议么?它基本上看起来像以前一样,但是这次它重新路由到root_url。 – dblarons 2013-03-08 08:24:44

+0

实际上取决于'checked_average_with_profile'动作的内容。你可以在你的问题中加入吗? – jvnill 2013-03-08 11:47:47

0

把你的paren放在user_likes_selection.id之后,而不是最后。您正在将图片标签属性与您的link_to属性混合在一起。

尝试:

<%= link_to image_tag(user_likes_selection.page_picture, :image_id =>  
user_likes_selection.id), {:controller => :preferences, 
:action => :checked_average_with_profile} %> 
+0

我将paren移至您指定的位置,但仍未激活控制器方法。另外,快速的问题,我写:preferences_controller或只是:首选项? – dblarons 2013-03-08 08:28:08

+0

对不起,迟到了,在我的iPad上昨晚。我更新了答案 – 2013-03-08 12:37:45

0

这是我在我的代码怎么办简化您的链接。

<%=link_to(image_tag(user_likes_selection.page_picture), check_average_profile_path(user_likes_selection.id)) %> 
0

尝试:

<%= link_to image_tag(user_likes_selection.page_picture), url_for({:controller => 'preferences_controller', :action => 'checked_average_with_profile', :image_id => user_likes_selection.id}) %> 
-1

加入收藏与我的资源行动终于解决了我的问题:

resources :preferences do 
    collection do 
    get 'save_new_scores_to_profile' 
    get 'checked_average_with_profile' 
    end 
end 

然后,我修改了我的视图代码,这样我可以通过image_id随控制器一起变化。

<%= link_to image_tag(user_likes_selection.page_picture, 
    checked_average_with_profile_preferences_path(:image_id => 
    user_likes_selection.id) %> 

在我的控制,我就确定抢使用参数的image_id并把redirect_to的结尾:

def checked_average_with_profile 
    params[:image_id] 
    redirect_to preferences_url 
end 

如果你有这个问题,关键部件均经过ID(无论这可能是)在您指定的控制器路径的括号内,并在路由文件中使用COLLECTION而不是MEMBER。