2014-02-23 89 views
3

我是編程的新手,所以這可能是一個簡單的問題。Ruby on Rails 4,設計和配置文件頁面

大約一個月前我開始使用RoR。不幸的是,我碰到了一個碰撞,似乎無法克服它。我試着尋求其他SO問題的幫助,但我仍然是一個新手,所以編碼建議對我來說仍然有點陌生。我希望有人可以把新東西變得更加友好。

我想要做的是讓我的網站爲註冊的每個用戶設置一個配置文件。這將是一個只有用戶和管理員才能訪問的私人配置文件。在用戶註冊/登錄後,我希望將他們重定向到他們的個人資料,他們可以在這裏編輯年齡和體重等信息。

我花了最近3天試圖找出如何獲得爲每個新用戶創建的個人資料頁面。我看了Devise github自述文件,但我仍然難倒了。

我已經生成了一個用戶控制器和用戶視圖,但我甚至不知道自從我設計之後是否需要執行這些步驟。任何幫助你可以給我,將不勝感激。

這裏是我的GitHub頁面的鏈接 - 在ApplicationControllerhttps://github.com/Thefoodie/PupPics

謝謝

回答

9

繼格爾登的答案,你需要真正有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 

模式

profiles 
id | user_id | name | birthday | other | info | created_at | updated_at 

路線

#config/routes.rb 
resources :profiles, only: [:edit] 

控制器

#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 

查看

#app/views/profiles/edit.html.erb 
<%= form_for @profile do |f| %> 
    <% @attributes.each do |attr| %> 
     <%= f.text_field attr.to_sym %> 
    <% end %> 
<% end %> 

然後,您需要聘請after_sign_in_path東西格爾登發佈


更新

這裏是遷移你會使用:

# 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 
+0

真棒,我實際上已經創建了一個user_profiles腳手架來照顧大部分。我希望我可以讓你和Kirti的答案都得到滿足,但我還沒有代表。該網站正在將用戶重定向到他們自己的個人資料頁面,現在我需要弄清楚如何將他們自己的個人信息放在該頁面上。 – user3254679

+0

感謝您的反饋 - 希望它有幫助!您可以使用我製作的代碼來顯示您需要的數據! –

+0

你如何將該模式添加到數據庫? –

7

首先你需要設置after_sign_in_path_forafter_sign_up_path_for你的資源,這將直接向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 

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 

此外,請確保您爲用戶創建一個view個人資料。

+1

謝謝你的幫幫我!當我獲得更多的聲譽時,我一定會回來並且提出這個答案。 – user3254679