2017-02-14 86 views
0

我正在嘗試使用RoR進行電子商務店鋪。大多數我所需要的功能沒有任何問題,但現在我真的需要某人的幫助。Rails創建動態屬性

我想製作產品屬性,如「尺寸」,「重量」,「顏色」等。 最簡單的方法是在模型遷移中定義此屬性,但現在我想使屬性成爲動態。主要的問題是,當我嘗試創建產品時,我無法從表單中獲取所有帶有屬性的參數。

產品/ new.html.erb

<%= form_for @product, url: admin_products_path(@product) do |f| %> 
    <%= f.label :name, 'Name' %> 
    <%= f.text_field :name, class: "form-control" %> 
    <%= text_field_tag "product[product_feature][]" %> 
    <%= text_field_tag "product[product_feature][]" %> 
    <%= f.submit "Submit" %> 
<% end %> 

所以,我想生成屬性名稱和值多領域,填補它們,並使用這些PARAMS在控制器interate他們最後創造的產品屬性。

params[:product_features].each do |k, v| 
    ProductFeature.create(name: k, value: v, product_id: product_id) 
end 

所有的寶石,可與動態屬性不使用Rails 5+工作操縱,所以我需要找到這個問題的解決方案。

我甚至已經爲此工作了簡單的數據庫解決方案,但創建參數並不舒服。這裏是。

Product.rb

class Product < ApplicationRecord 
    has_many :product_features 
    has_many :features, :through => :product_features 
end 

ProductFeature.rb

class ProductFeature < ApplicationRecord 
    belongs_to :product 
    belongs_to :feature 
end 

Feature.rb

class Feature < ApplicationRecord 
end 
+0

對我聽起來像一個嵌套的屬性就可以解決這個http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ ClassMethods.html –

回答

-1

繼承人快例如,我發現

class Product 
     belongs_to :collection 
    end 

    class Collection 
     has_many :products 
    end 

,然後在您的看法是這樣的

<%= collection_select(:product, :collection_id, Collection.all, :id, :name) %>