2011-12-15 89 views
0

一次保存/創建2個對象並將它們相互關聯時遇到問題。目前,我正在通過不使用嵌套窗體並將兩個對象的參數分開(從視圖中)傳遞給控制器​​,然後將它們連接到控制器中,這是我的代碼:Rails3關聯和嵌套屬性

模型

class Post < ActiveRecord::Base 
    belongs_to :user 
    has_one :product 
    accepts_nested_attributes_for :product, :allow_destroy => true 
end 

class Product < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :post 
end 

查看

<%= form_for(@post) do |f| %> 
     <div id="post_field"> 
      <%= f.text_area :content %> 
     </div> 
     <div id="post_link_previewer" class="clearfix"> 
     <%= fields_for :product do |prod| %> 
      <%= prod.text_field :name %><br /> 
      <%= prod.text_area :description, :rows => 2 %><br /> 
      <%= prod.text_field :image_url %><br /> 
      <%= prod.text_field :original_url %> 
     <% end %> 
     </div> 
     <div id="submit" class="clearfix"> 
      <%= f.submit "Post" %> 
     </div> 
     <% end %> 

PostsController

def create 
    @user = current_user 
    @post = @user.posts.create(params[:post]) 
    @product = Product.create(params[:product]) 
    @post.product_id = @product.id 

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to(root_path, :notice => 'Post was successfully created.') } 
     format.xml { render :xml => @post, :status => :created, :location => @post } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

因此,當用戶發佈帖子時,如果他們想要,他們可以將「產品」附加到該帖子。目前我做這件事的方式很有道理。當我查看嵌套的表單教程並使用構建方法查看它們時,我開始對發生的事情有點困惑。你能幫助我理解在創建時連接這兩個對象的最佳方式嗎?是否最好使用嵌套的表單域?我覺得目前我所做的並不像應該那樣高效。

回答

0

是的,你應該使用嵌套窗體。有一個原因,爲什麼他們建造。它們可以簡化管理關聯和一次創建嵌套對象的過程。

build方法構建一個對象(它調用對象的.new()方法),然後您可以使用它。

我建議你從嵌套表單的一個簡單例子開始,並使用它來玩一兩個小時。這樣,你就能更好地理解底下發生的事情。

我認爲,在這種情況下,通過遊戲自學會幫助你很多,而不是有人告訴你爲什麼嵌套形式更好。請參考nested-attributes-in-rails

+0

謝謝!再次通過它並使用build_association方法,我發現了我的嚴重錯誤,我把外鍵放在了錯誤的桌子上! – yoshyosh 2011-12-15 22:07:34