0
如何獲得此Rails f.select以停止在數據庫中保存空白字符串?我的API提交和數據庫提交都得到200,但數據庫和API都發送空白字符串。Rails f.select僅保存空白字符串而不是選項值
查看代碼
<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]]