我的应用程序需要在用户的购物车中多次复制技能(来自技能索引)。所以我决定在提交相关表单,包括重复数和Skill的id时,触发skills_controller的add-to-cart方法。为此,我在技能控制器的强参数中添加了计数器。
不幸的是,我缺少正确设置表单的一些东西:提交时,它会触发create方法。这是代码:
routes.rb提取
resources :skills, :path => "variables" do
resources :values_lists
member do
post :add_to_cart
get :create_values_list
get :upload_values_list
get :remove_values_list
end
collection do
get :index_all
end
end
Skills_controller.rb方法
def add_to_cart
@template_skill = Skill.find(params[:id])
iterations = params[:skill][:counter].to_i
until iterations == 0
@skill = @template_skill.deep_clone include: [:translations, :values_lists]
@skill.business_object_id = session[:cart_id]
@skill.template_skill_id = @template_skill.id
@skill.code = "#{@template_skill.code}-#{Time.now.strftime("%Y%m%d:%H%M%S")}-#{iterations}"
@skill.is_template = false
@skill.save
iterations -= 1
end
@business_object = BusinessObject.find(session[:cart_id])
redirect_to @business_object, notice: t('SkillAdded2BO') # 'Skill successfully added to business object'
end
index.html.erb表格内容
<tbody>
<% @skills.each do |skill| %>
<tr data-href="<%= url_for skill %>">
<% if not session[:cart_id].nil? %>
<td>
<%= form_with model: @skill, :action => "add_to_cart", :method => :post, remote: false do |f| %>
<%= f.text_field :counter, value: "1", class: "mat-input-element", autofocus: true %>
<button type="submit" class="mat-icon-button mat-button-base mat-primary add-button" title="<%= t('AddToUsed') %>">
<span class="fa fa-plus"></span>
</button>
<% end %>
</td>
<% end %>
<td class="no-wrap"><%= skill.code %></td>
<td><%= link_to skill.translated_name, skill %></td>
<td><%= link_to translation_for(skill.parent.name_translations), skill.parent %></td>
<td><%= skill.responsible.name %></td>
<td><%= skill.updated_by %></td>
<td class="text-right"><%= format_date(skill.updated_at) %></td>
</tr>
<% end %>
</tbody>
非常感谢你的帮助!