Rails f.select仅保存空白字符串而不保存选项值

时间:2017-04-19 17:20:58

标签: ruby-on-rails forms

如何让这个Rails f.select停止在数据库中保存空白字符串?我在API提交和数据库提交方面都获得了200分,但数据库和api都发送了空白字符串。

查看代码

<a href="#" class="button" id="new-suggestion-button" onclick="newSuggestionToggle(event)">New Suggestion</a>

<div id="new-suggestion-info">
  <h1>New Suggestion</h1>
  <%= form_for @suggestion, url: { action: "create" }, remote: true do |f| %>
    <div>  
      <%= f.select :name, options_for_select(@snacks.collect { |snack| snack["name"] if !snack["optional"] }), {}, { id: "snack-select", onchange: "otherSelected()" } %>
    </div>

    <br>
    <div id="other-snack-info">
      <h1>New Snack</h1>
      <div>
        <%= f.label :name %>
        <%= f.text_field :name %>
      </div>
      <div>
        <%= f.label :purchase_location %>
        <%= f.text_field :purchase_location %>
      </div>
    </div>
    <div>
      <%= f.hidden_field :optional, value: false %>
      <%= f.submit 'Submit' %>
    </div>
  <% end %>
</div>

控制器代码

def index
    api_key = ENV["API_KEY"]
    @snacks = Unirest.get("https://address_is_correct" + api_key).body 
    @snacks << { "name" => "Other" }
    @suggestion = Suggestion.new
  end

  def create
    api_key = ENV["API_KEY"]
    Unirest.post("https://address_is_correct" + api_key,
      headers:{ "Accept" => "application/json" }, 
      parameters: { 
        name: params[:name], 
        optional: params[:optional], 
        purchase_location: params[:purchase_location],
        purchase_count: params[:purchase_count],
        last_purchase_date: params[:last_purchase_date]
      }
    ).body

    @suggestion = Suggestion.new(suggestion_params)

    if @suggestion.save
      respond_to do |format|
        format.html
        format.js { render "create" }
      end
    end
  end

  private

    def suggestion_params
      params.require(:suggestion).permit(
        :name,
        :optional,
        :purchase_location,
        :purchase_count,
        :last_purchase_date
      )
    end

在终端中传递的参数如下所示

[["name", ""], ["optional", false], ["purchase_location", ""], ["created_at", 2017-04-19 17:09:46 UTC], ["updated_at", 2017-04-19 17:09:46 UTC]]

1 个答案:

答案 0 :(得分:0)

正如您可能看到的输出,所选名称未到达服务器端。这意味着问题在前端处理。

我的猜测是,因为你有2个名称属性元素(1个选择,1个输入),所以你的选择值不会被提交,因为输入放在select元素之后。尝试删除输入元素或在选项选择时禁用它。