我有一个rails应用程序!
我想为product
模型创建表单,用户可以先选择产品类别,然后填写表单。
这很容易,但我想根据所选类别向他们展示不同的属性。如果他们选择图书类别,那么他们会有title
,author
,published_at
等字段,但如果他们选择鞋类,那么他们可以填写size
, color
和type
字段。
我看到了关于动态表单的一些内容,但据我所知,我并不需要,因为表单字段将被预定义,用户无法添加额外的字段。
在这种情况下,有什么好办法?我应该创建更多不同的模型,例如(shoes
,books
等)或其他什么?
答案 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.