I have a form on Rails where I add some fields to the database, it adds the text fields properly but it always adds the select value as null, I populated the options with javascript
new.html.erb
<%= form_for @person, url: people_path, remote: false do |f| %>
<div class="form-group row"><label class="col-sm-2 col-form-label">*Name</label>
<div class="col-sm-3">
<%= f.text_field :name, class:"form-control" %>
</div>
</div>
<div class="form-group row"><label class="col-sm-2 col-form-label">*Country</label>
<div class="col-sm-3">
<%= select_tag :hcountry, nil, class:"select2_demo_1 form-control" %>
<%=hidden_field_tag 'country'%>
</div>
<label class="col-form-label">State</label>
<div class="col-sm-3">
<%= select_tag :hcity, nil, class:"select2_demo_1 form-control"%>
</div>
<script language="javascript">
populateCountries("hcountry", "hcity");
</script>
</div>
<!-- Buttons -->
<div class="hr-line-dashed"></div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-2">
<%= f.submit :Submit , class: 'btn btn-primary btn-sm'%>
<%= link_to "Cancel", controller:"mainpages", action:"index", :html=>{:class=> "btn btn-primary btn-sm"}%>
</div>
</div>
<% end %>
hidden-fields.js
$( "#hcountry" ).change(function() {
var h = $("#hcountry").val();
$("#country").val(h);
});
people_controller.erb
def new
@person = Person.new
end
def create
@person = Person.new(person_params)
if @person.save
redirect_to :root
end
end
private
def person_params
params.require(:person).permit(:name,:country, :city)
end
The javascript part is working since I wrote an alert to print the hidden field's value and it's actually printing the selected value, the problem is that it shows null in the database.
I didn't show the javascript to populate the options because it's way too long and I don't consider it relevant.
Use f.hidden_field :country
instead of hidden_field_tag 'country'
and chenge your script to update the value of #person_country
instead of #country
.
The way you have the code now the "country" value won't be nested inside params[:person]
, it will be just params[:country]
. Check the elements' ids and names, and check the params on the server log and you'll see that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.