【问题标题】:Restful Authentication -- Relating User ID to ProfileRestful 身份验证——将用户 ID 与配置文件相关联
【发布时间】:2011-01-07 21:28:40
【问题描述】:

我是 Ruby on Rails 的新手...我一直在开发一个社交网络类型的应用程序...我刚刚成功地将 Restful 身份验证添加到我的应用程序中...现在我想创建一个模型/controller 每个用户一旦登录就可以创建/编辑他们自己的配置文件。

所以我创建了模型和控制器……Profile 控制器中的代码如下所示:

def new
  @profile = Profile.new(params[:user_id])
  if request.post?
      @profile.save
      flash[:notice] = 'Profile Saved'
      redirect_to :action => 'index'
  end
end

我正在尝试将会话中的任何用户的 [restful auth.] 用户 ID 连接到我在配置文件模型中创建的列 user_id。我已经将“has_one:profile”添加到用户模型和配置文件模型中的“belongs_to:user”......但它没有添加配置文件。我有点卡住了,因为我对此比较陌生...我应该在会话模型或控制器中添加一些东西吗?

任何帮助、想法或研究地点都将不胜感激......

将新模型连接到现有模型非常重要,我想弄清楚这一点。

【问题讨论】:

    标签: ruby-on-rails database model-view-controller entity-relationship


    【解决方案1】:

    默认情况下,new 操作是 HTTP GET,所以您的 request.post?块被绕过。 request.post?无论如何都是无关的(出于基本目的),所以我会完全摆脱它并将save 代码的其余部分移至您的create 操作。

    def new
      @profile = Profile.new
    end
    
    def create
    
      @user = User.find(params[:user_id])
      @profile = Profile.create(@user, params[:profile]) # or whatever params you use in your form
      # you can also do @profile = @user.profile.create(params[:profile]) here
      # sans @user find: @profile = current_user.profile.create(params[:profile])
    
      if @profile.save
        flash[:notice] = 'Profile Saved'
        redirect_to :action => 'index'
      else
        flash[:warning] = 'Could not save profile'
        redirect_to :back # or wherever
      end
    
    end
    

    【讨论】:

      【解决方案2】:

      首先,如果您刚刚开始,您应该认真考虑使用Authlogic 而不是 Restful 身份验证。没有生成器,您最终会得到非常易于管理的代码。

      对于这个特定问题:@profile.save 记录的创建应该在 create 操作中。 new 是关于为表单设置模型实例以在 new.html.erb 视图上对其进行编辑。

      您还可以访问称为@current_user 的方法(或称为current_user 的函数)。如果你这样做了,你可以通过这样做来缓解一些事情:

      @profile = current_user.profile.build
      

      build 方法将为您创建用户和个人资料之间的关联。

      【讨论】:

        猜你喜欢
        • 2018-03-26
        • 2018-09-09
        • 2016-10-18
        • 2019-12-22
        • 2018-02-20
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 1970-01-01
        相关资源
        最近更新 更多