2013-05-03 3 views
1

언뜻보기에이 질문은 이전에 대답 한 것처럼 보이지만 내 경우에는 그렇지 않습니다. 대부분은 대량 할당 문제 및/또는 몽고이드와 관련이 있습니다. 여기에 관련 질문이 많지만 답변을드립니다.중첩 된 특성을 추가하여 사용자 모델을 생성하십시오.

그래서 기본적으로 레일즈 애플리케이션의 루비 사용자 인증을 위해 devise gem을 사용하고 있으며 중첩 된 주소 모델을 사용자 모델에 추가하려고합니다. 또한 simple_form을 사용하여 양식보기를 생성합니다.

class Address < ActiveRecord::Base 
    belongs_to :country 
    belongs_to :state 
    belongs_to :user 

    attr_accessible :street1, :street2, :country_id, :state_id, :city, :postalCode 
end 

이 내가 사용자 프로필을 표시하는 show 액션을 추가하기 위해 오버라이드 Users (사용자) 컨트롤러입니다 :

class User < ActiveRecord::Base 
    has_and_belongs_to_many :roles 
    has_one :address 

    accepts_nested_attributes_for :address, :allow_destroy => true 
end 

이 주소 모델은 다음과 같습니다

나는 사용자 모델을 가지고 .

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> 

       <fieldset> 
        <%= f.input :username, :required => false, :autofocus => true, placeholder: 'Pick a username' %> 
        <%= f.input :email, :required => false, placeholder: 'Your email' %> 
        <%= f.input :password, :required => false, placeholder: 'Create a password' %> 
        <%= f.input :password_confirmation, :required => false, placeholder: 'Confirm your password' %> 
        <%= f.association :roles, :as => :check_boxes, :label => "", :required => false %> 
        <%= f.simple_fields_for :address do |a| %> 
         <%= a.input :street1 %> 
         <%= a.input :street2 %> 
         <%= a.association :country %> 
         <%= a.association :state %> 
         <%= a.input :city %> 
         <%= a.input :postalCode %> 
        <% end %> 
        <%= f.button :submit, 'Sign up for free', :class => 'btn btn-success btn-large' %> 
       </fieldset> 
<% end %> 

그래서 새로운 사용자를 생성시 오류가 이것이다 :

class Users::RegistrationsController < Devise::RegistrationsController def new resource = build_resource({}) resource.build_address respond_with resource end # POST /resource def create resource = build_resource(params[:user]) if resource.save if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_navigational_format? sign_up(resource_name, resource) respond_with resource, :location => after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format? expire_session_data_after_sign_in! respond_with resource, :location => after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource respond_with resource end end def show @user = User.find(params[:id]) #Add to view count if not viewing own user profile if @user != current_user @user.views += 1 @user.save end @vehicles = Vehicle.where(:user_id => @user) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end end 

만들고 새로운 사용자를위한이다 주소 사용자는 비워 둘 수 없습니다

기본적를 외래 키 user_id가 주소로 설정되어 있지 않습니다.

나는 누군가가이 문제에 관해 약간의 비평을하기를 바랬다.

+0

사용자와 주소 관계에 대해'inverse_of'를 설정해 보셨습니까? – OutlawAndy

+0

다른 방법으로'user_id'가 설정되도록하는 또 다른 방법은'UsersController # new' 액션에서'@address = @ user.build_address'이고, 폼에서는'@ address'를 중첩 된 폼의 객체로 사용하십시오. 모든 사용자가 주소를 만들지는 않을 것임을 명심하십시오. – OutlawAndy

+0

안녕하세요, Andy! 나는 두 가지 제안을 고려했다. : inverse_of는 아무것도하지 않았고 같은 문제가 발생했습니다. 그런 다음 제안 된대로 새로운 작업 및보기 필드를 변경했습니다. 이제 다음 예외가 발생합니다. ActiveRecord :: AssociationTypeMismatch in Users : RegistrationsController # create – robvelor

답변

0

마이그레이션을 해결하기 위해 user_id를 추가 잊으. Rails는 belongs_to : user를 주소 모델에 추가 할 때이를 예상했습니다.

0

내 응용 프로그램에서이 문제를 해결할 수 있었지만 강력한 매개 변수를 사용하고 있습니다. 그러나 솔루션은 귀하의 경우에도 여전히 적용 가능해야합니다.

RegistrationsController의 모든 메서드를 재정의하는 대신 필요한 올바른 매개 변수를 전달하기 위해 build_resource을 오버로드했습니다.

def build_resource(params) 
    super(resource_params) 
end 

def resource_params 
    params.require(:user).permit(:email, :password, tickets_attributes: [ :description ]) 
end 

나는이처럼, 내 UserTicket 모델에 inverse_of 있습니다

user.rb 
    has_many :tickets, inverse_of: :user 

ticket.rb 
    belongs_to :user, inverse_of :tickets 
+0

안녕하세요 Jeff,이 기능이 작동하지 않습니다. 솔루션을 시도하고 다시보고 해 드리겠습니다. 최대한 빨리 해결책을 제안 해 주셔서 감사합니다. – robvelor

관련 문제