2013-08-18 61 views
3

我有一個用戶的顯示頁面,Rails4:連接到控制器

1)路線

get 'users/:id' => 'user#show', as: :user 

2)user_controller.rb

class UserController < ApplicationController 

before_filter :authenticate_user!, only: :show 

def show 
    @user = User.find_by_name(params[:id]) # for name instead of id 
@listings = @user.listings 
end 
end 

,我可以鏈接到它通過「current_user」。

我想創建一個店控制器,所以我按照相同的步驟。我生成的商店控制器和修改的路線和控制器如下:

1)路線

get 'users/:id' => 'user#show', as: :user 
get 'shop/:id' => 'shop#show', as: :shop 

2.)shop_controller.rb

class ShopController < ApplicationController 

before_filter :authenticate_user!, only: :show 

def show 
    @user = User.find_by_name(params[:id]) # for name instead of id 
    @listings = @user.listings 
end 

end 

這在用戶僅工作如果即時通訊頁面(localhost:3000/users/test),然後單擊鏈接到控制器。然後切換到(localhost:3000/shop/test)。

,如果我嘗試任何地方點擊鏈接其他即時得到

enter image description here

的鏈接 - >

<li><%= link_to "My Shop", :controller => "shop", :action => "show" %></li> 

我是相當新的Rails的,如果有人能賜教它將是非常好:)

+0

嗨。你真的想通過名字找到用戶嗎?我認爲使用id是一種更好的方法。 – Bot

+0

這是嚴格的視覺和功能。但我不認爲這是問題:( –

+0

我認爲我是我的鏈接是錯誤的,但我仍然在黑暗中 –

回答

2

首先開始更正您的控制器的名稱按照軌道約定。名字應該如下。

控制器/ users_controller.rb

class UsersController < ApplicationController 

before_filter :authenticate_user!, only: :show 

    def show 
     @user = User.find(params[:id]) # Because Id can't be same for two users but name can be. 
     @listings = @user.listings 
    end 
end 

而且在shop_controller的情況下,它是精細怎麼一回事,因爲店鋪不是模型。

控制器/ shop_controller.rb

class ShopController < ApplicationController 

before_filter :authenticate_user!, only: :show 

def show 
    @user = User.find(params[:id]) # Id can't be same for two users but name can be. 
    @listings = @user.listings 
end 

end 

並給這樣的鏈接。

<%= link_to "My Wonderful Shop", {:controller => "shop", :action => "show", :id => @user.id} %> 

在你的路由文件

get 'shop/:id' => 'shop#show' 
+0

仍然收到該錯誤。我認爲這與鐵路如何獲得商店有關:id或知道在哪裏鏈接。 –

+0

Thanks that worked :) –

+0

由於您使用了'as::shop',因此您應該可以使用<%= link_to'我的商店',shop_path(@user)%>'創建鏈接。 –