【问题标题】:Ruby on Rails: Getting a route with DeviseRuby on Rails:使用 Devise 获取路线
【发布时间】:2015-05-11 15:44:52
【问题描述】:

TL;DR我怎样才能做到这一点,以始终使用 Mongoid 在自定义控制器中返回具有设计用户模型 ID 的路由(即重定向到 localhost:3000/profiles/504026426)?

我有一个项目,它有一个社交配置文件控制器,它使用 Devise 返回一个用户 ID,但它总是抱怨 Mongoid 需要一个有效的 ID 号才能使用此路由:localhost:3000/profiles/。

# Let's say I want to return a route with id (Devise) without having
# Rails to complain that Mongoid needs to a id of some number.

# So, I have controller containing profiles in the files.
# It goes like..
class ProfilesController < ApplicationController
  before_filter :authenticate_user!
    # GET /profile/
    def index
      @user = User.find(params[:id])
    end
    # .. Snipped for brevity.
end

这是正确的做法吗?

【问题讨论】:

    标签: ruby ruby-on-rails-4 devise mongoid


    【解决方案1】:

    首先,您尝试查找用户的 'params[:id]' 在索引视图中不起作用,因为您没有通过 url 传递任何参数('profiles/:id'或:本地主机:3000/profiles/504026426)。如果您想存储用户在索引视图中可用,请使用会话和当前用户帮助器方法。见here。

    如果您希望您的 GET 方法与 'params[:id]' 一起使用,它看起来像:

    get 'profile/:id' => 'profiles#show'
    

    确保它与控制器中的显示功能匹配

    def show
      # this would work with: localhost:3000/profiles/504026426
         @user = User.find(params[:id])
    end
    

    【讨论】:

    • Rails 现在抱怨缺少模板。上面的参考代码对我有用。不过,它想根据路由 mkdir views/profile。
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 2011-02-15
    • 2011-10-26
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多