2014-12-03 77 views
1

我正在創建一個來自不同模型的屬性的嵌套表單。我希望在保存新對象之前,所有必需的屬性都是有效的。Rails - 如何驗證具有嵌套屬性的表單?

<%= form for @product do |f| %> 

    <%= f.fields_for @customer do |g| %> 

    <%= g.label :name %> 
    <%= g.text_field :name %> 

    <%= g.label :email %> 
    <%= g.text_field :email %> 

    <%= g.label :city %> 
    <%= g.text_field :city %> 

    <%= g.label :state %> 
    <%= g.text_field :state %> 

    <%= g.label :zipcode %> 
    <%= g.text_field :zipcode %> 

    <% end %> 

    <%= f.label :product %> 
    <%= f.text_field :product %> 

    <%= f.label :quantity %> 
    <%= number_field(:quantity, in 1..10) %> 

<% end %> 

這裏是我的模型

class Product < ActiveRecord::Base 

    belongs_to :customer 
    validates_associated :customer 
    validates :product, :presence => "true" 

end 

class Customer < ActiveRecord::Base 

    has_one :product 
    validates :name, :email, presence: true 
    validates :email, format: { with: /[A-Za-z\d+][@][A-Za-z\d+][.][A-Za-z]{2,20}\z/ }    
    validates :city, presence: true 
    validates :zipcode, format: { with: /\A\d{5}\z/ } 

end 

我加validates_associated我的產品型號,所以我的form_for @product應該要求所有的客戶驗證通過。這意味着名稱,電子郵件,城市和郵政編碼必須在那裏,並且必須正確格式化。

我亂了一下,提交了表格,沒有填寫客戶要求的字段,表格被認爲是有效的。

我不明白我的錯誤在哪裏。

編輯

好了,所以加入validates :customer,現在需要的客戶屬性。但它們實際上並未保存到數據庫中。我認爲這與我的參數有關

def product_params 
    params.require(:product).permit(:product, :quantity) 
end 

是否需要將我的客戶參數添加到我的允許參數列表中?

回答

2

嘗試了這一點:

在控制器如下創建產品的實例和相關的客戶:

@product = Product.new 
    @customer = @product.build_customer 

在使用這種代碼形式

<%= form for @product do |f| %> 

    <%= f.fields_for :customer do |g| %> 

    <%= g.label :name %> 
    <%= g.text_field :name %> 

    <%= g.label :email %> 
    <%= g.text_field :email %> 

    <%= g.label :city %> 
    <%= g.text_field :city %> 

    <%= g.label :state %> 
    <%= g.text_field :state %> 

    <%= g.label :zipcode %> 
    <%= g.text_field :zipcode %> 

    <% end %> 

    <%= f.label :product %> 
    <%= f.text_field :product %> 

    <%= f.label :quantity %> 
    <%= number_field(:quantity, in 1..10) %> 

<% end %> 

我。e使用:客戶符號而不是@customer實例變量。

和使用產品型號accepts_nested_attributes_for輔助方法@Charles說

3

如果對象存在的validates_associated方法只驗證關聯的對象,因此,如果您離開表單字段爲空,則Product正在創建/編輯將驗證,因爲沒有相關的Customer

相反,假設您使用的是Rails 4+,則需要使用accepts_nested_attributes_for :customer以及validates :customer, presence: true以便在您的產品表單中要求客戶字段。

如果您使用的是Rails 3,那麼accepts_nested_attributes_for將不適用於belongs_to關聯。相反,您的Customer課程將需要使用accepts_nested_attributes_for :product,您需要相應地更改表單視圖。

UPDATE

你也需要讓你的控制器動作來接受參數爲:customer協會:

def product_params 
    params.require(:product).permit(:product, :quantity, :customer_attributes => [:name, :email, :city, :state, :zipcode]) 
end 

值得一提的是,因爲在你的客戶表單字段沒有:id場,並且在產品表單字段中沒有:customer_id字段,則每次成功提交產品表單時都會創建一個新客戶。

+0

OK,我嘗試添加'驗證:customer'現在需要的那場。但是當我輸入字段時,它說它缺失。這一定是因爲我的參數。我會看看我能否解決這個問題 – Darkmouse 2014-12-03 04:28:42