根据类别导出不同的表单属性

时间:2016-02-14 08:40:18

标签: ruby-on-rails forms activerecord attributes

我有一个rails应用程序!

我想为product模型创建表单,用户可以先选择产品类别,然后填写表单。

这很容易,但我想根据所选类别向他们展示不同的属性。如果他们选择图书类别,那么他们会有titleauthorpublished_at等字段,但如果他们选择鞋类,那么他们可以填写sizecolortype字段。

我看到了关于动态表单的一些内容,但据我所知,我并不需要,因为表单字段将被预定义,用户无法添加额外的字段。

在这种情况下,有什么好办法?我应该创建更多不同的模型,例如(shoesbooks等)或其他什么?

1 个答案:

答案 0 :(得分:1)

Should I create more different models

No, I don't think that's necessary.

What you'd be best doing is using ajax to populate the form on category change. This would require some configuration, but will make it the most efficient and secure:

#config/routes.rb
resources :products do
  put :new, on: :new #-> url.com/products/new
end

#app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def new
    if request.get?
      @product    = Product.new
      @categories = Category.all
    elsif request.put?
      @category   = params[:product][:category_id]
      @attributes = ...
    end

    respond_to do |format|
      format.js
      format.html
    end 
  end
end

#app/views/products/new.html.erb
<%= form_for @product do |f| %>
   <%= f.collection_select :category_id, @categories, :id, :name, {}, { data: { remote: true, url: new_product_path, method: :put }} %>
   <div class="attributes"></div>
   <%= f.submit %>
<% end %>

#app/views/products/new.js.erb
$attributes = $(...); // need a way to create form elements from @attributes
$("form#new_product .attributes").html( $attributes );

Something important to note is that Rails select & check elements allow you to use the data-remote attribute to send an ajax call to your controller on change.

Not much documentation about it, playing around with the above code should get it to work.

相关问题