2016-04-25 56 views
1

我在Rails的這樣一個完整的初學者,我試圖建立一個頁面中添加一次用戶登錄額外的配置文件數據NoMethodErrorRails的:與色器件模型創建HAS_ONE協會

我使用設計的認證的目的,並且工作正常。我得到這個錯誤,我一直在這裏卡住。

未定義的方法`個人資料

能否請你幫忙嗎?

代碼

profiles_controller.rb

class ProfilesController < ApplicationController 

    before_action :authenticate_user!, only: [:new, :create, :show] 

    def new 
    @profile = current_user.profiles.build 
    end 

    def create 
    @profile = current_user.profiles.build(profile_params) 
    if @profile.save 
     format.html {redirect_to @profile, notice: 'Post was successfully created.'} 
    else 
     format.html {render 'new'} 
    end 

    end 

    def show 
    @profile = current_user.profiles 
    end 

    private 

    def profile_params 
    params.require(:profile).permit(:content) 
    end 
end 

的誤差似乎從特別

def new 
    @profile = current_user.profiles.build 
    end 

其它碼這些行來以供參考:

/views/profiles/new.html.erb

<h1>Profiles#new</h1> 
<p>Find me in app/views/profiles/new.html.erb</p> 

<h3>Welcome <%= current_user.email %></h3> 

<%= form_for(@profile) do |f| %> 

    <div class="field"> 
    <%= f.label :content %><br /> 
    <%= f.text_field :text, autofocus: true %> 
    </div> 

    <div class="actions"> 
    <%= f.submit "Sign up" %> 
    </div> 
<%end%> 

的routes.rb

Rails.application.routes.draw do 
    get 'profiles/new' 

    get 'profiles/create' 

    get 'profiles/show' 

    get 'profiles/update' 

    get 'pages/home' 

    get 'pages/dashboard' 

    devise_for :users, controllers: { registrations: "registrations" } 
    resources :profiles 


    root 'pages#home' 

    devise_scope :user do 
    get "user_root", to: "page#dashboard" 
    end 
end 

型號/ user.rb

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_one :profile, dependent: :destroy 
end 

型號/配置文件.rb

class Profile < ActiveRecord::Base 

    belongs_to :user 
end 
+0

您可以發佈完整的錯誤添加方法指標?另外,你可以發佈你的用戶模型嗎? –

+0

嘿安東尼, 我只是想通了!關係是* has_one *。 因此,它應該是'@profile = current_user.build_profile'而不是'@ profile = current_user.profiles.build' –

回答

1

您試圖調用一個未定義的關係:

def new 
    @profile = current_user.profiles.build 
    end 

    has_one :profile 

你應該叫:

def new 
    @profile = current_user.build_profile 
    end 
+0

謝謝Jorge。但是這給出了構建方法沒有定義。 我只是想通了。它在文件中:( –

1

1)如果您的用戶必須有很多配置文件。設置在你的應用/模型/用戶。RB has_many :profiles

2)在新的方法中您ProfilesController而不是@profile = current_user.profiles使用@profile = Profile.new

3)在你的routes.rb刪除

get 'profiles/new' 

    get 'profiles/create' 

    get 'profiles/show' 

    get 'profiles/update' 

,因爲你已經使用resources :profiles

4)要保持DRY的規則,您可以從部分渲染表單。只需在new.html.erb中添加視圖/ profiles/_form.html.erb中的相同內容,然後刪除所有內容即可new.htm.erb並粘貼<%= render "form" %>。將來它會幫助你渲染編輯表單,如果你想。

5)在你ProfilesController你可以用所有配置

def index 
    @profiles = Profile.all 
end