我的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>
单击图像时为什么不执行控制器代码?
答案 0 :(得分: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)
答案 1 :(得分:0)
在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} %>
答案 2 :(得分:0)
以下是我在代码中的操作方式。
<%=link_to(image_tag(user_likes_selection.page_picture), check_average_profile_path(user_likes_selection.id)) %>
答案 3 :(得分: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}) %>
答案 4 :(得分:-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) %>
在我的控制器中,我确保使用params获取image_id并在最后放置一个redirect_to:
def checked_average_with_profile
params[:image_id]
redirect_to preferences_url
end
如果您遇到此问题,关键部分是在您指定的控制器路径的括号内传递id(无论可能是什么),并在路由文件中使用COLLECTION而不是MEMBER。