【问题标题】:Rails create dynamic attributesRails 创建动态属性
【发布时间】:2017-02-14 12:32:44
【问题描述】:

我正在尝试使用 RoR 制作电子商务商店。大多数必需的功能我都没有任何问题,但现在我真的需要有人帮助。

我想制作产品属性,例如“尺寸”、“重量”、“颜色”等。 最简单的方法是在模型迁移中定义这个属性,但现在我想让属性动态化。主要问题是我在尝试创建产品时无法从表单中获取所有带有属性的参数。

产品/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[:product_features].each do |k, v|
  ProductFeature.create(name: k, value: v, product_id: product_id)
end

所有可以使用动态属性操作的 gem 都不适用于 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

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-5 rails-activerecord


【解决方案1】:

创建一个新模型,一个名为 ProductAttribute 的具有两个属性的子产品。

Class ProductAttribute < ApplicationRecord
  belongs_to :product

  validates :name, presence: true
  validates :value, presence: true
end

然后使用cocoon,或者只使用accepts_nested_attributes

class Product < ApplicationRecord
  has_many :product_attributes, as: :attributes
  accepts_nested_attributes_for :attributes, allow_destroy: true
end
class ProductsController < ApplicationController
.
.
.
  private
  .
  .
  def product_params
    params.require(:product).permit(. . . attributes_attributes: [:id, :name, :value])
  end
end

Cocoon 绝对是您想要的。

【讨论】:

    【解决方案2】:

    这是我找到的一个简单示例

    class Product
          belongs_to :collection
        end
    
        class Collection
          has_many :products
        end
    

    然后在你看来是这样的

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

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 2022-06-24
      • 2018-12-10
      • 2019-05-02
      • 1970-01-01
      • 2021-09-12
      • 2022-01-16
      相关资源
      最近更新 更多