2011-08-30 68 views
0

我想在創建/編輯商店(子模型)時保存來自用戶(父模型)的數據。保存關聯模型的問題

我的模型:

class User < ActiveRecord::Base 
    has_one :shop, :dependent => :destroy 
end 

class Shop < ActiveRecord::Base 
    belongs_to :user 
    accepts_nested_attributes_for :user #!!!!!!!!!!!! 
end 

我的店鋪控制器:

class ShopsController < ApplicationController 
    def new 
     @shop = Shop.new 
     #@shop.user = current_user 
     @shop.build_user 
    end 
end 

def create 
    @shop = Shop.new(params[:shop]) 

    @shop.user = current_user 
    respond_to do |format| 
    if @shop.save 
     flash[:notice] = t(:shop_created) 
     format.html { redirect_to(@shop) } 
     format.xml { render :xml => @shop, :status => :created, :location => @shop } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @shop.errors, :status => :unprocessable_entity } 
    end 
end 

end 

店鋪頁:

<% form_for @shop, :html => {:multipart => true} do |f| %> 
    <%- f.fields_for :user do |user| %> 
     <%= user.text_field :name, :live => true %> 
    <% end -%> 
<% end -%> 

所有的例子,我發現有關保存關聯模型從用戶保存時(父母)N個孩子(我的商店模型)。在這些情況下,我明白了定義accept_nested_attributes_for的位置。

我的情況是相反的。

問:如何在Shop窗體上提交時保存用戶數據?

回答

0

看一下文檔,accept_nested_attributes_for是爲了在父模型上,在這種情況下是用戶。所以,如果你做相反的事情,並保存在用戶模型上,當傳遞商店嵌套屬性時,它應該工作。我不得不承認我沒有嘗試過這個,但這是我從閱讀中得到的結果:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+0

是的,我明白你的意思,你所描述的是「accepted_nested_attributes_for」的典型用法(也許是唯一的)。但在我的情況下,我不想通過提交用戶表單而是通過商店表單來保存用戶數據。也許我應該面對不同的方法,如果accept_nested_attributes_for不適合我的情況。也許這裏的正確問題是:在孩子表單上提交時,哪種方法可以最好地保存父母數據? – ratamaster

+0

我不知道是否有一種更漂亮的方式來做到這一點,除了創建一個方法作爲商店模型的一部分,抓取它的用戶父對象並單獨設置屬性值。基本上使用params哈希值,手動指定每個鍵以返回該模型的每個字段所需的值。 – agmcleod

+0

是的,這正是我所做的。謝謝 ! – ratamaster