2012-10-04 5 views
1

저는이 문제로 몇 시간 동안 곤두박질 쳤습니다. 누군가이 코드가 작동하지 않는 이유를 알아낼 수 있기를 바랍니다.레일에서 has_one 연관 문제가 있습니다.

내가하려는 것은 특정 사용자와 관련된 계정을 만드는 것입니다. 사용자를 만들 수는 있지만 계정을 만들 때 폼이 내 컨트롤러의 create 메서드에 게시하는 것처럼 보이지 않습니다 (양식 데이터의 배열이 브라우저 막대에 계정/새로 추가됨) . 여기

내 모델입니다 :

class User < ActiveRecord::Base 
    attr_accessible :email_address, :password, :password_confirmation 
    has_secure_password 
    has_one :account, dependent: :destroy 

    before_save {|user| user.email_address = email_address.downcase} 

그리고 내 계정 모델 : 내 사용자 컨트롤러에서

class Account < ActiveRecord::Base 
    attr_accessible :cell_phone, :first_name, :home_phone, :last_name, :middle_initial, :work_phone 
    belongs_to :user 
    has_many :addresses 
    has_many :orders 
    has_many :items 

    #strip digits and return string of numbers 
    before_save do |account| 
    account.cell_phone = cell_phone.gsub(/\D/,'') 
    account.home_phone = home_phone.gsub(/\D/,'') 
    account.work_phone = work_phone.gsub(/\D/,'') 
    end 

    before_save do |account| 
    account.first_name = first_name.capitalize 
    account.last_name = last_name.capitalize 
    account.middle_initial = middle_initial.capitalize 
    end 

(이 제대로 작동) :

def new 
    if signed_in? 
     @user = current_user 
     redirect_to @user 
    else 
     @user = User.new 
    end 
    end 

    def create 
    @user = User.new(params[:user]) 
    if @user.save 
     sign_in @user 
     redirect_to new_account_path 
    else 
     flash[:error] = "Sorry, something went wrong" 
     render 'new' 
    end 
    end 

그리고 내 계정 컨트롤러 (문제가있는 것 같아요.) :

class AccountsController < ApplicationController 
    #before_filter :get_current_user 
    before_filter :signed_in_user 

    def new 
    @user = current_user 
    @account = @user.build_account(params[:account]) 
    end 

    def create 
    @user = current_user 
    @account = @user.build_account(params[:account]) 
    if @account.save 
     flash[:success] 
     redirect_to user_path(current_user) 
    else 
     flash[:error] 
     redirect_to root_path 
    end 
    end 

필자는 도우미 파일에서 current_user 및 sign_in을 메소드로 사용합니다.

그리고, 마지막으로, 내 계정 양식 당신의 도움에 미리

<%= form_for(@account) do |form| %> 
    <%= render 'shared/user_form_error_messages', object: form.object %> 

    <%= form.label :first_name, "First Name" %> 
    <%= form.text_field :first_name %> 

    <%= form.label :middle_initial, "Middle Initial (optional)" %> 
    <%= form.text_field :middle_initial %> 

    <%= form.label :last_name, "Last Name" %> 
    <%= form.text_field :last_name %> 

    <%= form.label :home_phone, "Home Phone" %> 
    <%= form.text_field :home_phone %> 

    <%= form.label :cell_phone, "Cell Phone" %> 
    <%= form.text_field :cell_phone %> 

    <%= form.label :work_phone, "Work Phone" %> 
    <%= form.text_field :work_phone %> 

    <%= form.submit "Complete Account", class:"btn" %> 

<% end %> 

감사합니다. 나는 예를 찾고, rdocs를 읽고 여러 가지를 시도했다. 누군가 내 코드가 왜 작동하지 않는지 설명 할 수 있다면 (단지 답을 제공하는 것과 반대), 나는 가장 감사 할 것입니다. 이 될 것입니다

Started GET "/accounts/new? utf8=%E2%9C%93&authenticity_token=DQ5mOiICI0C83l9xgkSlvToQKyWjE3Adm3X3U0HJ1W4%3D&account%5Bfirst_name%5D=Jesse&account%5Bmiddle_initial%5D=A&account%5Blast_name%5D=Flores&account%5Bhome_phone%5D=555-555-5555&account%5Bcell_phone%5D=&account%5Bwork_phone%5D=&commit=Complete+Account" for 127.0.0.1 at 2012-10-04 16:14:11 -0400 
Connecting to database specified by database.yml 
Processing by AccountsController#new as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"DQ5mOiICI0C83l9xgkSlvToQKyWjE3Adm3X3U0HJ1W4=", "account"=>{"first_name"=>"Jesse", "middle_initial"=>"A", "last_name"=>"Flores", "home_phone"=>"555-555-5555", "cell_phone"=>"", "work_phone"=>""}, "commit"=>"Complete Account"} 
    User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'B_E1bsUASQhHC-Zb-6updg' LIMIT 1 
    Account Load (0.6ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."user_id" = 2 LIMIT 1 
    (0.1ms) begin transaction 
    (0.0ms) commit transaction 
    Rendered shared/_user_form_error_messages.html.erb (0.5ms) 
    Rendered forms/_form_account.html.erb (5.9ms) 
    Rendered accounts/new.html.erb within layouts/application (13.2ms) 
    Rendered layouts/_navigation.html.erb (0.4ms) 
    Rendered forms/_form_header_signin.html.erb (0.8ms) 
    Rendered layouts/_header.html.erb (2.7ms) 
    Rendered layouts/_messages.html.erb (0.5ms) 
    Rendered layouts/_footer.html.erb (0.3ms) 
Completed 200 OK in 279ms (Views: 160.1ms | ActiveRecord: 4.6ms) 
+0

질문을 업데이트하고 양식 게시 프로세스가있는 곳에 로그 부분을 추가하십시오. – thesis

+0

@thesis는 이것이 무엇을 의미합니까? – jflores

답변

0

미안 해요, 내가 먼저 문제를 오해. 그러나 기존 user 개체를 새 account과 연결하려는 것 같습니다. 여기에 도움이 될만한 링크가 있습니다.

https://stackoverflow.com/a/11335976/1160106

큰 문제 설명하지만, 명확하고 간단한 대답

. 그것이 너를 돕는 지 알려줘.

+0

제안에 감사드립니다. 그러나 그것은 효과가 없었습니다. 다음 명령을 따르는 경로 경로 (예 : 사용자 아래에 중첩 된 단일 리소스 사용)를 수정했지만 # <# <클래스 : 0x007fd9b4046e98> : 0x007fd9b4046e98>에 대한 정의되지 않은 메소드 'user_accounts_path'가 있습니다. – jflores

+0

'user_accounts_path' 대신에'user_account_path'가되어서는 안됩니까? 'accounts'가'account'라고 확인하십시오. '레이크 루트 '는 무엇을 보여줍니까? – Samiron

+0

Samiron에게 감사드립니다. 많은 도움이되었습니다.양식을 제출할 때 자동으로 작성 메소드에 게시 될 것이라고 가정했습니다. 그래서 build_account와 .save 메소드를 'new'메소드에 넣고 거기에서 계정 생성을 처리하고 있습니다. – jflores

0

희망이 코드에서 중첩 된 인스턴스를 구축하기위한 작업을 수행하는 데 도움을줍니다 내가 양식에 "전송"버튼을 클릭 할 때 @thesis 요청에

, 여기에 내 로그에서 출력됩니다. accountscontroller에서 ,

def new 
    @user = current_user 
    @account = @user.accounts.build(params[:account]) 
    end 

    def create 
    @user = current_user 
    @account = @user.accounts.build(params[:account]) 
    if @account.save 
     flash[:success] 
+0

안녕하세요 shanmuk, 귀하의 제안에 감사드립니다. 불행히도, 그것은 작동하지 않습니다. 그것은 has_one 관계이기 때문에 빌드 나 생성 메소드를 사용하는 Active Record 객체가 없습니다. Rails 문서에 따르면 build_association 또는 create_association 메서드를 사용하여 연결된 레코드를 만들어야합니다. – jflores

관련 문제