实例变量字符串集合在render =>之后丢失'新'

时间:2013-09-11 22:52:42

标签: ruby-on-rails session simple-form instance-variables

当我在创建引号时出错,它会呈现它刚刚显示的同一页面并显示错误。不幸的是,两个输入是字符串的下拉菜单,当刷新发生时它们会消失。

我看过Rail 3: instance variable not available after redirection谈论会话,看起来这可能是正确的方式,但我不确定。任何帮助将不胜感激。

引用控制器

def new
    @quote = Quote.new
    @quote.items.build
    @types = ["T-Shirt", "Hoodie", "Sweatpants"]
    @colors = ["White", "Black", "Red", "Blue", "Green"]
end

def create
@quote = Quote.new(params[:quote])
  respond_to do |format|

  if @quote.save

    format.html { redirect_to root_url }
    flash[:success] = "Your quote is being approved. You will recieve an email shortly!"
    format.json { render json: @quote, status: :created, location: @quote }
  else
    format.html { render :action => 'new' }
    format.json { render :json => @quote.errors, :status => :unprocessable_entry }
    flash[:error] = "Quote failed to create! Try again!"
  end
 end
end

形成部分

<!-- item form -->
<%= f.input :make, collection: @types, label: 'Thread Type' %>
<%= f.input :amount, label: 'How Many' %>
<%= f.input :color, collection: @colors %>
<!-- nested form for creating a design of an item -->
<%= f.simple_fields_for :designs, :html => { :multipart => true } do |designform| %>
    <%= render "customdesign", g: designform %>
  <% end %>
<!-- add/remove another design -->  
<%= f.link_to_add "Add Design", :designs %>
<%= f.input :note, :input_html => { :cols => 50, :rows => 3 }, label: 'Special Notes or Requests' %>
<%= f.link_to_remove "Remove" %>

1 个答案:

答案 0 :(得分:0)

@colors@types仅在new操作中设置,而不在create操作中设置。渲染模板不会自动调用控制器中的action方法;它直接进入视野。

一种可能的解决方案是为这些列表定义辅助方法:

# app/helpers/quote_helper.rb
module QuoteHelper
  def possible_types
    ["T-Shirt", "Hoodie", "Sweatpants"]
  end
end

在你看来:

<%= f.input :make, collection: possible_types, label: 'Thread Type' %>