2013-03-08 130 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。