2011-12-01 109 views
0

我有一個公司有一個訂閱。現在我想要一個表單來添加或編輯公司和訂閱,所以我使用「accep_nested_attributes_for」。這是(的一部分)的公司模式:一對一關係的嵌套屬性

has_one :subscription, :dependent => :destroy 
    accepts_nested_attributes_for :subscription 

這是(部分)的訂閱模式:

belongs_to :company 

在控制器我有這樣的:

def new 
    @company = Company.new(:subscription => [Subscription.new]) 
    end 

    def create 
    @company = Company.new(params[:company]) 

    if @company.save 
     redirect_to root_path, notice: I18n.t(:message_company_created) 
    else 
     render :action => "new" 
    end 
    end 

    def edit 
    @company = Company.find(params[:id]) 
    end 

    def update 
    @company = Company.find(params[:id]) 

    if @company.update_attributes(params[:company]) 
     redirect_to root_path, :notice => I18n.t(:message_company_updated) 
    else 
     render :action => "edit" 
    end 

    end 

而表格看起來像這樣:

 <%= f.fields_for(:subscription) do |s_form| %> 
     <div class="field"> 
      <%= s_form.label I18n.t(:subscription_name) %> 
     <%= s_form.text_field :name %> 
     </div> 
    <% end %> 

這給出了2個專業版blems:

  • 名稱字段只顯示在當一個公司已經擁有了訂閱編輯形式,它不添加一個新的公司
  • 時,當編輯公司更改註冊名稱秀場,更改不會被保存。

我在這裏做錯了什麼?

我使用的Rails 3.1版本

回答

2

我想你應該改變你的新行動:

def new 
    @company = Company.new 
    @company.build_subscription 
end 

docs進一步的信息。那麼我認爲您必須將subscription_attributes添加到您公司定義的attr_accessible列表中。