我是新来的,所以我希望新帐户能够立即提出问题。我现在已经和Rails合作了一段时间,通常我很擅长研究和解决自己的问题 - 但是这个问题让我感到难过了几天。
我在控制器中调用了一个创建操作,该控制器包含一个基于check_box post参数的条件if-else语句。我可以看到参数被发布到控制器,所以语句应该能够正确分支,但发生了一些奇怪的事情。控制器执行语句的两个分支,但因为我的参数根据check_box进行修剪,所以第二个分支总是出错。我相信这与路线没什么关系。
请参阅下面的代码:
控制器:
def create
@quote = Quote.find(params[:quote_id])
if params[:quote_item][:custom] == 1
@quote_item = @quote.quote_items.new(quote_item_params)
@quote_item.rate = nil
@quote_item.custom = true
@quote_item.unit_price = params[:quote_item][:unit_price]
@quote_item.rate_name = params[:quote_item][:title]
else
@quote_item = @quote.quote_items.new(quote_item_params)
@quote_item.custom = false
@rate = Rate.find(params[:quote_item][:rate_id])
@quote_item.unit_price = @rate.price
@quote_item.rate_name = @rate.product.name
end
respond_to do |format|
if @quote.save
format.html { redirect_to @quote, notice: 'Quote item was successfully added.' }
format.json { render :show, status: :created, location: @quote }
else
format.html { redirect_to @quote }
format.json { render json: @quote.errors, status: :unprocessable_entity }
end
end
查看:
<% if @rates.any? %>
<%= bootstrap_form_for([@quote, @quote_item], layout: :inline) do |f| %>
<%= f.text_field :title, class: 'input-sm', hide_label: true, :placeholder => "Line Title" %>
<%= f.select(:rate_id, @rates.collect {|r| [r.select_summary_text, r.id ] }, { hide_label: true }, { :class => 'input-sm' }) %>
<%= f.number_field :quantity, class: 'input-sm', hide_label: true, :min => 1, :length => 2, :value => 1 %>
<%= f.text_field :unit_price, class: 'input-sm', hide_label: true, :min => 1, :length => 2, :prepend => "$" %>
<%= f.text_field :note, class: 'input-sm', hide_label: true, :placeholder => "Note (Optional)" %>
<%= f.submit "Add Quote Item", class: 'btn btn-sm btn-default' %>
<%= f.check_box :custom, label: "Override" %>
<% end %>
<% else %>
<div class="well well-sm"><i class="fa fa-usd"></i> No pricing for this customer has been set. Set product pricing for this jobs customer <%= link_to user_path(@quote.job.user) do %>here.<% end %></div>
<% end %>
我的创建方法错误在这里:
@rate = Rate.find(params[:quote_item][:rate_id])
使用:
ActiveRecord::RecordNotFound (Couldn't find Rate with 'id'=):
app / controllers / quote_items_controller.rb:19:在'create&#39;
但是这个错误是正确的,因为在if-else语句的第一个分支中没有处理速率ID。我尝试过不同的check_box表单字段,直接覆盖&#39; custom&#39;两个分支仍在运行。
非常感谢任何帮助!
答案 0 :(得分:0)
params哈希包含字符串。
尝试交换:
if params[:quote_item][:custom] == '1'
原作:
if params[:quote_item][:custom] == 1