我是 Rails 新手。我正在开发一个网络应用程序,用户可以在其中插入鞋子库存。因此,用户输入款式代码、尺寸、价格和数量。我想要数量来定义数据库中有多少条目。因此,如果数量为三,则将为每只鞋创建三个单独的行。目前,每个表单提交都会在数据库中创建一行。
我在我的鞋 Controller 中创建:
def create
@shoe = Shoe.new(shoe_params)
respond_to do |format|
if @shoe.save
format.html { redirect_to @shoe, notice: 'Shoe was successfully created.' }
format.json { render :show, status: :created, location: @shoe }
else
format.html { render :new }
format.json { render json: @shoe.errors, status: :unprocessable_entity }
end
end
end
我的_form.html.erb
<%= form_with(model: shoe, local: true) do |form| %>
<% if shoe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(shoe.errors.count, "error") %> prohibited this shoe from being saved:</h2>
<ul>
<% shoe.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :sku %>
<%= form.text_field :sku %>
</div>
<div class="field">
<%= form.label :size %>
<%= form.text_field :size %>
</div>
<div class="field">
<%= form.label :quantity %>
<%= form.number_field :quantity %>
</div>
<div class="field">
<%= form.label :price %>
<%= form.text_field :price %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
我需要做出哪些改变才能达到我想要的结果? 谢谢!
最佳答案
@rohit 是正确的,因为使用 Shoe.create
方法可以获得您想要的东西。但要实现这一点,您可以将 Controller 更改为以下内容。我确信有更简洁的方法可以做到这一点,但它应该可以满足您的需求。另外,我建议验证 Shoes_params 中的数量是否为正整数。
def create
@show = Show.new(shoe_params)
# This will create an array of shoes from your params
new_shoes = (1..shoe_params[:quantity]).collect { Shoe.new(shoe_params) }
# Save each record and put the result in an array
success = new_shoes.map(&:save)
if success.all?
# all records saved
else
# maybe @shoe.valid? is false or something else happened
end
end
关于mysql - rails : How to let user input define how many entries are recorded into the database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453544/