2016-04-25 32 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