Ruby on Rails 4,Devise和profile页面

use*_*679 4 ruby-on-rails user-profile devise ruby-on-rails-4

我是编码的新手,所以这可能是一个简单的问题.

我大约一个月前开始使用RoR.不幸的是,我遇到了磕磕碰碰,似乎无法克服它.我已经尝试过寻求其他SO问题寻求帮助,但我仍然是新手,所以编码建议对我来说仍然有些陌生.我希望有人可以把事情变得更加新手友好.

我想要做的是让我的网站为每个注册用户设置一个配置文件.这将是一个私人配置文件,只有用户和管理员才能访问.在用户注册/登录后,我希望将他们重定向到他们的个人资料,在那里他们可以编辑年龄和体重等信息.

我花了最近3天试图弄清楚如何为每个新用户创建一个个人资料页面.我查看了Devise github自述文件,但我仍然难过.

我已经生成了用户控制器和用户视图,但我甚至不知道自从我设计以来是否需要执行这些步骤.你们可以给我的任何帮助将不胜感激.

这是我的github页面的链接 - https://github.com/Thefoodie/PupPics

谢谢

Ric*_*eck 10

继Kirti的回答之后,您需要实际profile重定向到:

楷模

#app/models/profile.rb
Class Profile < ActiveRecord::Base
    belongs_to :user
end

#app/models/user.rb
Class User < ActiveRecord::Base
    has_one :profile
    before_create :build_profile #creates profile at user registration
end
Run Code Online (Sandbox Code Playgroud)

架构

profiles
id | user_id | name | birthday | other | info | created_at | updated_at
Run Code Online (Sandbox Code Playgroud)

路线

#config/routes.rb
resources :profiles, only: [:edit]
Run Code Online (Sandbox Code Playgroud)

调节器

#app/controllers/profiles_controller.rb
def edit
   @profile = Profile.find_by user_id: current_user.id
   @attributes = Profile.attribute_names - %w(id user_id created_at updated_at)
end
Run Code Online (Sandbox Code Playgroud)

视图

#app/views/profiles/edit.html.erb
<%= form_for @profile do |f| %>
    <% @attributes.each do |attr| %>
       <%= f.text_field attr.to_sym %>
    <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

然后你需要使用after_sign_in_pathKirti发布的东西


更新

以下是您要使用的迁移:

# db/migrate/[[timestamp]]_create_profiles.rb
class CreateProfiles < ActiveRecord::Migration[5.0]
  def change
    create_table :profiles do |t|
      t.references :user
      # columns here
      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Kir*_*rat 8

首先,您需要设置after_sign_in_path_forafter_sign_up_path_for为您的资源ApplicationController指定profile页面.然后你需要创建一个controller将呈现profile页面.

例如:(根据您的要求更改)

ApplicationController定义路径

  def after_sign_in_path_for(resource)
    profile_path(resource)
  end

  def after_sign_up_path_for(resource)
    profile_path(resource)
  end
Run Code Online (Sandbox Code Playgroud)

ProfilesController

  ## You can skip this action if you are not performing any tasks but,
  ## It's always good to include an action associated with a view.

  def profile

  end
Run Code Online (Sandbox Code Playgroud)

此外,请确保view为用户配置文件创建.