2013-12-13 9 views
0

사용자 및 프로필을위한 일대일 모델이 있습니다.레일에서 일대일 관계 모델에 form_for 사용

다음은 기기에서 생성 한 User 모델의 코드입니다.

class User < ActiveRecord::Base 
    has_one :profile , dependent: :destroy 
end 

코드 Profile 모델.

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

는 지금은 가입시 생성 된 User에 대한 Profile 기본 있습니다. 이제 도우미 장치를 사용하여 사용자 프로필을 편집하는 방법은 current_userform_for을 제공합니까?

답변

0

우리는이 같은 짓 : 당신이 사용자를 저장하면이 데이터베이스의 프로파일 레코드를 채 웁니다

#app/models/user.rb 
Class Model < ActiveRecord::Base 
    before_create :build_profile 
end 

, 당신은

에 나중에 업데이트 할 수 있도록를, 당신이 사용하는 가장 좋은 것 accepts_nested_attributes_for 다음과 같이 사용자에 대한 양식을 통해 & profile 저장 옵션을 채울 :

#config/routes.rb 
resources :users do 
    resources :profiles 
end 

#app/views/profiles/edit.html.erb 
<%= form_for @profile do |f| %> 
    <%= f.hidden_field :user_id, current_user.id %> 
    <%= f.text_field :your_profile_options %> 
<% end %> 

목 is는 그것을하는 아주 기본적인 방법이지만, 잘하면 당신에게 더 많은 아이디어를 줄 것이다. 이 문제를보고 싶다면 http://video-conference-demo.herokuapp.com (사용자를 처리하기 위해 Devise를 사용하십시오. &에는 "프로필"모델이 있습니다)