2016-04-25 4 views
1

Я полный новичок в Rails, как, например, и я пытаюсь построить страницу, чтобы добавить дополнительные данные профиля, как только пользователь входит вRails:. NoMethodError по созданию 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

Hey Anthony, Я только что понял! Отношение: * 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

Спасибо, Хорхе. Но это дает метод сборки не определен. Я только что понял. Это было в документации :( –

1

1) Если пользователь должен имеют много профилей. Устанавливается в вашем приложении/модели/пользователе.гь 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, вы можете визуализировать форму из частичного. Просто добавьте в views/profiles/_form.html.erb тот же контент в свой new.html.erb, после чего вы можете удалить все im new.htm.erb и вставить <%= render "form" %>. В будущем это поможет вам отредактировать форму, если хотите.

5) В вашем ProfilesController вы можете добавить индекс метод со всеми профилями

def index 
    @profiles = Profile.all 
end 
Смежные вопросы