2015-01-08 5 views
3

위치, 전기, 어쩌구, 어쩌구, 등등으로 Devise 사용자에 대한 별도의 프로필 모델을 만들려고합니다. 문제는 데이터베이스에 저장할 수 없다는 것입니다.레일에서 Devits 사용자와 프로필 모델

내 사용자는 "아티스트"라고합니다.

### /routes.rb ### 

get 'artists/:id/new_profile' => 'artists/profiles#new', as: :profile 
post 'artists/:id/new_profile' => 'artists/profiles#create' 

### artists/profiles_controller.rb ### 

class Artists::ProfilesController < ApplicationController 

    before_action :authenticate_artist! 

    def new 
    @artist = current_artist 
    @profile = ArtistProfile.new 
    end 

    def create 
    @artist = current_artist 
    @profile = ArtistProfile.new(profile_params) 
    if @profile.save 
     redirect_to current_artist 
    else 
     render 'new' 
    end 
    end 
end 

### /artist.rb ### 

class Artist < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable 
    has_one :artist_profile, dependent: :destroy 

### /artist_profile.rb ### 

class ArtistProfile < ActiveRecord::Base 
    belongs_to :artist 
    validates :artist_id, presence: true 
end 

### /views/artists/profiles/new.html.erb ### 

<%= form_for(@profile, url: profile_path) do |f| %> 
    <div class="field"> 
    <%= f.label :biography, "biography", class: "label" %> 
    <%= f.text_area :biography, autofocus: true , class: "text-field" %> 
    </div> 
    <div class="field"> 
    <%= f.label :location, "location", class: "label" %> 
    <%= f.text_field :location, class: "text-field" %> 
    </div> 
    ... 
    ... 
    ... 
    <div class="actions"> 
    <%= f.submit "create profile", class: "submit-button" %> 
    </div> 
<% end %> 

여기서 내가 뭘 잘못하고 있니?

답변

2

current_artist 개체를 사용하여 프로필을 초기화해야합니다.

class Artists::ProfilesController < ApplicationController 
    before_action :authenticate_artist! 

    def new 
    @artist = current_artist 
    @profile = @artist.build_profile 
    end 

    def create 
    @artist = current_artist 
    @profile = @artist.build_profile(profile_params) 
    if @profile.save 
     redirect_to current_artist 
    else 
     render 'new' 
    end 
    end 
end 

업데이트 :

이 예제를 사용하려면 사용자의 연결이 컨트롤러에서

class Artist < ActiveRecord::Base 
    has_one :profile, class_name: ArtistProfile 
end 
0

저장하기 전에 프로필의 artist_id를 설정해야합니다.

@profile = ArtistProfile.new(profile_params, artist_id: @artist.id) 

또는

@profile = ArtistProfile.new(profile_params) 
@profile.artist_id = @artist.id 

작동합니다.

0

처럼 당신이 profile_params 방법을 누락해야합니다.

private 

def profile_params 
     params.require(:profile).permit(:biography, :location) 
end