我有表单,当我提交此表单时,rails会使用params重定向到new_admin_item_path
,但我需要添加到app_f.input :gost, as: :select
所选的选项,我该怎么办?
这是我的表格。
form(:html => { :multipart => true }) do |f|
f.inputs "Item" do
f.input :name, label: 'Имя', :input_html => { :value => params[:name] }
f.input :category_id, as: :select, collection: SubCategory.all, :selected => params[:category_id]
f.input :size
f.input :wall_th, label: "Толщина стенки"
f.input :price, :input_html => { :value => params[:price] }
end
f.inputs do
f.has_many :item_gosts, allow_destroy: true, new_record: true do |app_f|
if !app_f.object.nil?
# show the destroy checkbox only if it is an existing appointment
# else, there's already dynamic JS to add / remove new appointments
app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
end
app_f.input :gost, as: :select, collection: if params[:id].present?
Item.find(params[:id]).sub_category.gosts.all
else
Gost.all
end
#app_f.input :item_gosts # it should automatically generate a drop-down select to choose from your existing patients
end
f.has_many :item_steel_marks, allow_destroy: true, new_record: true do |app_f|
if !app_f.object.nil?
# show the destroy checkbox only if it is an existing appointment
# else, there's already dynamic JS to add / remove new appointments
app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
end
app_f.input :steel_mark, as: :select, collection: if params[:id].present?
Item.find(params[:id]).sub_category.steel_marks.all
else
SteelMark.all
end
end
f.input :description, :input_html => { :value => params[:description] }
end
f.button "Сохранить"
end
这是一个活跃的admin cotroller。
controller do
def new
@item = Item.new
end
def create
@item = Item.create(item_params)
if @item.save
flash[:success] = "Товар добавлен"
redirect_to new_admin_item_path(:category_id => @item.category_id, :name => @item.name, price: @item.price, description: @item.description)
else
flash[:alert] = "ошибка"
render 'new'
end
end
答案 0 :(得分:1)
Formtastic(在AA中使用)has deprecated selected
option。
您可以使用options_for_select
。
看看例子:
collection: options_for_select([1,2,3], 2) # will make 2 a default value
所以在你的情况下你可以尝试:
app_f.input :gost,
as: :select,
collection: options_for_select( (params[:id].present? ? Item.find(params[:id]).sub_category.gosts.all : Gost.all), Gost.first) # will make `Gost.first` a default value.
在这种情况下,确保Gost.first
只是一个定义默认值的示例,您必须找出真正符合您要求的内容。
此部分(params[:id].present? ? Item.find(params[:id]).sub_category.gosts.all : Gost.all)
使用ternary
运算符,与if else
语句相比更短(但仍然相同)。