Ruby on rails Rails f.选择仅保存空白字符串而不保存选项值
如何让Rails f.select停止在数据库中保存空白字符串?API提交和数据库提交都得到了200分,但是数据库和API都发送了空字符串 视图代码Ruby on rails Rails f.选择仅保存空白字符串而不保存选项值,ruby-on-rails,forms,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
<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>
正如您在输出中看到的,所选名称不会到达服务器端。这意味着在前端处理问题 我的猜测是,由于name属性有2个元素(1个select,1个input),所以不会提交所选的值,因为输入放在select元素之后。尝试删除输入元素或在选项选择时禁用它
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]]