我有一个 rails4 应用程序。目前,我的收藏选择仅在我仅选择一个选项时才有效。下面是我的工作代码。我只有产品形式。行业模型由seeds.rb
. IndustryProduct 仅用于连接其他 2 个模型。
我想知道我必须在代码中进行哪些更改才能选择更多。
我看到了一些带有multiple: true
选项的工作示例(https://www.youtube.com/watch?v=ZNrNGTe2Zqk at 10:20),但在这种情况下,用户界面有点难看+无法使用任何示例来完成代码。是否有其他解决方案,例如选择一个选项的更多框而不是一个具有多个选项的框?
楷模:
class Product < ActiveRecord::Base
belongs_to :user
has_many :industry_products
has_many :industries, through: :industry_products
has_many :product_features
accepts_nested_attributes_for :industry_products, allow_destroy: true
accepts_nested_attributes_for :product_features
validates_associated :industry_products
validates_associated :product_features
end
class Industry < ActiveRecord::Base
has_many :industry_products
has_many :products, through: :industry_products
accepts_nested_attributes_for :industry_products
end
class IndustryProduct < ActiveRecord::Base
belongs_to :product
belongs_to :industry
end
_form.html.erb
<%= form_for @product do |f| %>
<%= render 'layouts/error_messages', object: f.object %>
......
<%= f.fields_for :industry_products do |p| %>
<%= p.collection_select :industry_id, Industry.all, :id, :name %>
<% end %>
<%= f.fields_for :product_features do |p| %>
<%= p.text_field :feature, placeholder: "add a feature", class: "form-control" %>
<% end %>
<%= f.submit class: "btn btn-primary" %>
<% end %>
产品控制器
def new
@product = Product.new
@product.industry_products.build
@product.product_features.build
end
def create
@product = current_user.products.new(product_params)
if @product.save
redirect_to @product
else
render action: :new
end
end
......
def product_params
params.require(:product).permit(....., industry_products_attributes: [:id, :industry_id, :_destroy], industries_attributes: [:id, :name], product_features_attributes: [:feature])
end