我正在尝试将Devise中的用户ID放在我的应用程序路由中。例如 (www.test.com/users/1/offers)
我的应用程序工作正常,但是当我在我的控制器中调用redirect_to而没有“用户”时,我遇到了路由匹配错误。
错误
没有路线匹配{:action =>“index”,:controller =>“offer”, :user_id => nil}缺少必需的键:[:user_id]
welcome_controller.rb(无需用户登录)
class WelcomeController < ApplicationController
def index
@skip_footer = true
if user_signed_in?
redirect_to user_offers_path(@user)
else
end
end
end
的routes.rb
devise_for :users
resources :users do
resources :offers do
member do
put :tourcomplete
end
end
end
任何帮助都会很棒!
修改
控制器
def index
if current_user.present?
@offers = Offer.all
else
redirect_to root_url
end
def tourcomplete
current_user.update_attributes(tourcomplete: true)
redirect_to root_url
end
@featured_offers = Offer.where(featured: true)
end
类别控制器
resources :categories, only: :show
答案 0 :(得分:2)
首先,我必须指出,在这种情况下您没有调用Devise
用户ID,您只是使用标准的Rails资源路由:
#config/routes.rb
resources :users do
resources :categories do #-> url.com/users/:user_id/categories
get :test, on: :collection
end
resources :offers do #-> url.com/users/:user_id/offers
put :tourcomplete #-> you don't need member do
end
end
#app/controllers/offers_controller.rb
class OffersController < ApplicationController
def index
@user = User.find params[:user_id]
@offers = @user.offers
end
end
这就是你的代码应该的使用方式。
因此,如果您想将其与Welcome
控制器一起使用,您可以按如下方式使用它:
#app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
redirect_to user_offers_path(current_user) if user_signed_in?
end
end
您的offers
控制器可以改进如下:
#app/controllers/offers_controller.rb
class OffersController < ApplicationController
before_action :authenticate_user!
def index
@offers = Offer.all
end
end
答案 1 :(得分:1)
您可以在控制器中添加before_action
,以获取所需的@user
,以便能够重定向到user_offers_path(@user)
。
类似的东西:
class WelcomeController < ApplicationController
before_action :set_user, only: [:index]
def index
@skip_footer = true
if user_signed_in?
redirect_to user_offers_path(@user)
else
end
end
private
def set_user
@user = User.find(params[:user_id])
end
end
当然,在调用WelcomeController的索引时,您还需要将user_id放在GET或POST参数中。