2012-12-11 41 views
0

我有兩個類,User和Contact。用戶有許多聯繫人,並且聯繫人屬於用戶。在用戶的秀觀,我有:如何更改Rails呈現的表單?

<%= link_to 'Add Contact', :controller => "contacts", :action => "new", :user => @user.id %> 

然後,在接觸的控制器,新的作用下,我有:

@user = User.find(params[:user]) 
@contact = Contact.new 
@contact.user = @user 

當新的接觸形式呈現,它具有#<用戶:用戶字段中已經有0x4c52940 >。但是,當我去提交表單時,出現錯誤:用戶(#39276468)預期,得到了字符串(#20116704)。

問題是,當創建被調用時,Ruby會取得表單中的所有內容並覆蓋新聯繫人中的字段。所以:我怎樣才能更改窗體來刪除用戶字段,以便用戶不會被字符串覆蓋?

編輯: 我聯繫的new.html.erb有這樣的:

<%= render 'form' %> 
<%= link_to 'Back', contacts_path %> 

聯繫的控制器:

def new 
@user = User.find(params[:user]) 
@contact = Contact.new 

@contact.user = @user 


respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @contact } 
end 
end 

def create 
@contact = Contact.new(params[:contact]) 

respond_to do |format| 
    if @contact.save 
    format.html { redirect_to @contact, notice: 'Contact was successfully created.' } 
    format.json { render json: @contact, status: :created, location: @contact } 
    else 
    format.html { render action: "new" } 
    format.json { render json: @contact.errors, status: :unprocessable_entity } 
    end 
end 
end 
+0

顯示您的看法。顯示你的模型關聯。 – deefour

+0

那是你想看到的嗎? – Chris

回答

1

我相信你濫用創造的作用控制器。從本質上講它的內容應該是像這樣

def create 
    @user = User.find(params[:user_id]) 
    contact = @user.contacts.build(params[:contact]) 
    if contact.save 
    flash[:alert] = 'New contact is created' 
    redirect_to contacts_path(contact) 
    else 
    flash.now[:error' = 'Error creating contract' 
    render :action => :new 
    end 
end 

所以+1以前的答案 - 告訴你控制器和新形式的代碼

+0

我編輯了一些更多的信息。這是你在找什麼?我是一名Rails初學者,所以我真的只是使用爲我生成的腳手架。 – Chris

相關問題