Using select_month in form_for - ruby-on-rails

I am working in Ruby on Rails and I cant figure out how to use select_month in a form_for. What I am trying is:
<%= form_for(#farm) do |f| %>
<div class="field">
<%= f.label :harvest_start %><br />
<%= select_month(Date.today, :field_name => 'harvest_start') %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
which is outputting
["harvest_start", nil]

In order to use select month consistently with the rest of your form builder, use date_select without the day or month:
date_select(object_name, method, options = {}, html_options = {})
Just use f.date_select :harvest_start, {order: [:month]} i.e. add order: [:month] or discard_year: true, discard_day: true to the options hash, as specified in the docs
The benefit of this you can pass in all the remaining options as you would in the options hash. Something like:
<%= f.date_select :birth_date, {prompt: true, order: [:month]}, class: 'form-control' %>

(this was answered in comments by T. Weston Kendall so just making it a proper answer)
the following code is what i got to work.
_form.html.erb
<div class="field">
<%= f.label :harvest_start %><br />
<%= f.collection_select :harvest_start, Farm::MONTHS, :to_s, :to_s, :include_blank => true %>
</div>
farms_controller.rb
#farm.harvest_start = params[:harvest_start]
i also got select_month to work but i needed the :include_blank and i didn't want to spend the time figuring out what to do with the nil in an array.

Related

Ruby on rails. Set a form field as nil/blank from controller

I am trying to let users RELIST 'gigs' that they have previously posted by duplicating the old one and saving it with a new ID. At the moment everything duplicates fine and can be saved but I need one of the fields (datetime) to be blank as it is vital that they manually set this. I do not know how to set this as nil/blank from the controller.
Relist link:
<%= link_to t('gigs.show.relist'), gig_relist_path(:gig_id => #gig.id), class: 'gig-edit-dash' %>
Gig controller:
def relist
#oldgig = Gig.find(params[:gig_id])
#gig = #oldgig.dup
end
Form:
<div class="create-form">
<%= simple_form_for #gig do |form| %>
<div class="create-title">
<%= form.input :title, label: t('gig.title'), placeholder: t('placeholder.title') %></div>
<div class="create-location">
<%= form.input :location, label: t('gig.location'), placeholder: t('placeholder.location') %></div>
<div class="create-genre">
<ul></ul>
<%= form.label :genres %>
<%= select_tag "choose_genres", options_from_collection_for_select(Genre.all, 'id', 'name',#gig.genres.map{ |j| j.id }), :multiple => true %> </div>
<div class="create-description">
<%= form.input :description, as: :text, label: t('gig.description'), placeholder: t('placeholder.description') %></div>
<div class="create-date">
<%= form.input :date, label: t('gig.date'), placeholder: t('placeholder.date') %></div>
<div class="create-salary">
<div class="salary-input">
<p class="salary-title"> <%= t('gig.salary') %> </p>
<%= form.input :salary_currency, label: false,
collection: ["€", "£", "$" ], prompt: "Choose one" %>
<%= form.input :salary, label: false, placeholder: t('placeholder.salary') %>
</div>
</div>
Setting the default value to nil/blank in the form doesn't work as a value is being passed.
#gig.date = nil
doesn't work either, this sets the time to the current time.
Oh dear, I just figured this out about 2 minutes after posting the question. I'll leave the answer rather than deleting the post just in case someone else finds it useful.
I set #gig.date = nil in the controller after #gig = #oldgig.dup
Then added , :include_blank => true to the form field in the view.
The reasoning is pretty self explanatory.

Rails 4 form: display database value in select field

There are similar questions on Stack Overflow, like this one or that one, and I tried what the answers recommended, but I could not fix my problem.
I have a Rails form — NOT a simple_form form — with the following field in my new view:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'] %>
</div>
Then, I want to re-display this form in my edit view, with the value that was saved to the database, so I tried:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'], :selected => current_user.price %>
</div>
The problem is that the select field displays the first value instead of the one I am expecting.
—————
UPDATE: Following the answers given below, I implemented the following code:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %>
<%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>
It does not seem to work. Unless I made a mistake?
—————
Any idea how to make this work?
You don't need two separate forms.
in new.html.erb and edit.html.erb put the following:
<%= render 'hourly_rate' %>
then in _hourly_rate.html.erb put the following:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %>
<%= f.select :price, options_for_select([['10',1], ['20',2], ['30',3], ['40',4], ['50',5], ['60',6], ['70',7], ['80',8], ['90',9], ['100',10]], #your_obj.price) %>
</div>
where #your_obj.price is something like 1, 2, 3...(or you can modify this to the actual prices if you'd prefer. You'd just need to change the arrays accordingly).
The options_for_select method is a helper whose second parameter allows you to pre-select an option by passing its value. For more on that, take a look at the docs.
try this:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>
you should pass an array of arrays which the left cell is the name and the right one is the value, then pass in selected by value and not by name, you should use this also in the first form:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']] %>
</div>

Rails 4 parameters hash not working correctly on update action

When I create a search the correct parameters are coming in fine in the rails 4 params hash via params[:search] but on the update action some of my parameters are not working via params[:search]. When I looked at the request for the update action I found what I was looking for( code directly below) but when using rails params hash I am only getting 4 of them( latter code ). Any ideas on how to fix this?
I am not talking about using the search_params function. I am talking about when debugging the app you can make sure the parameters are in the hash. If they are not in the params hash they will not show up no matter what your code looks like in search_params
"search"=>
{"gender"=>"2",
"height_low"=>"60",
"height_high"=>"70",
"weight_low"=>"80",
"weight_high"=>"110",
"age_low"=>"18",
"age_high"=>"33",
"city"=>"fg",
"province_state"=>"fg",
"country"=>"CA"}
"search"=>
{"gender"=>"2", "city"=>"fg", "province_state"=>"fg", "country"=>"CA"}
form
<%= form_for #search, url: {action: "update"}, html: { method: "post"} do |f| %>
<%= f.label :gender, 'Gender:' %>
<%= f.select(:gender, attractions, :selected => #search.gender) %>
<br />
<%= f.label :height_low, 'Height between:' %>
<%= f.select(:height_low, heights) %>
<%= f.select(:height_high, heights) %>
<br />
<%= f.label :weight_low, 'Weight between:' %>
<%= f.select(:weight_low, (80..300).to_a.map{|n| [n, n]}) %>
<%= f.select(:weight_high, (80..300).to_a.map{|n| [n, n]}) %>
<br />
<%= f.label :age_low, 'Age between:' %>
<%= f.select(:age_low, (18..100).to_a.map{|n| [n, n]}) %>
<%= f.select(:age_high, (18..100).to_a.map{|n| [n, n]}) %>
<br />
<%= f.label :city, 'City:' %>
<%= f.text_field :city, required: true %>
<%= f.label :province_state, 'Province or State:' %>
<%= f.text_field :province_state, required: true %>
<%= f.label :country, 'Country:' %>
<%= f.country_code_select :country, [[ 'United States', 'US' ], [ 'Canada', 'CA' ]] %>
<div><%= f.submit "Search" %></div>
search parameters in controller
private
def search_params
params.require(:search).permit(:age_low,:age_high,:weight_low,:weight_high,:height_low,:height_high,:gender,:screen_name,:city,:province_state,:country)
end
This isn't much to go on since there isn't any background information to how you are using this has. You might only be permitting specific values in your parameter hash? For example
def search_params
params.require(:search).permit(:gender, :city, :province_state, :country)
end
Maybe provide a little more information.

properly storing date info using form_for

I have a form that allows a user to create an event. One of the fields that the user fills out is date. Currently this is the code for the date filed:
<%= u.label :date %> <%= u.text_field :date, :placeholder => 'mm/dd/yyyy' %>
For some reason, if the user types in 01/02/2012 it stores as dd/mm/yyyy, thinking the event is on Feb 1 instead of Jan 2nd. I've already configured my initializer files to display date/datetime the way I would like it to (as recommended on several posts here) but this is still an issue
Update - here is my full form:
<%= form_for(#party_profile) do |u|%>
<p>
<%= u.label :name %><%= u.text_field :name %>
</p>
<p>
<%= u.label :location %><%= u.text_field :location %>
</p>
<p>
<%= u.text_field :date, :placeholder => 'dd/mm/yyyy' %>
</p>
<p>
<%= u.label :password %> <%= u.text_field :password %>
</p>
<%= u.submit "Let's Party!", :class => "btn btn-primary" %>
<% end %>
I have tried replacing u.text_field with select_date as suggested below, but then I get an error:
undefined method `select_date' for #<ActionView::Helpers::FormBuilder:0x007f9e5e8c69d8>
<%= u.label :date %> <%= u.date_select(:date, :order => [:month, :day, :year]) %>
is the best I could come up - still not formatted exactly how I'd like
I use that for my dates:
<%= u.label :date %>
<%= u.date_field :date %>
Hope it helps =)
Consider using select_date, rather than a simple text field where the user can type in anything.
<%= u.select_date(:date, :order => [:month, :day, :year]) %>
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-select_date

How do I submit the associated section of a form remotely in Rails without submitting the entire form?

I have a simple Rails form that allows for its associated parent to be edited. I would like to allow the user to submit this section of the form using :remote => true so that the user can add a new parent, and then select the parent in an updated select menu elsewhere in the form. As you can see in the code, I added a submit button to the parents' part of the form, and it even knows whether to say "Create" or "Update," but when I submit it the entire page is refreshed, the entire form is submitted for validation and so forth. How can I accomplish what I want in Rails?
Here is the code in question:
<%= form_for #sermon, :html => { :multipart => true } do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :date %><br />
<%= f.text_field :date %>
</div>
<div class="field">
<%= f.label "Speaker" %><br />
<%= f.select :speaker_id, Speaker.all.collect {|p| [ p.name, p.id ] }, {:include_blank => true} %>
</div>
<% #sermon.build_speaker unless #sermon.speaker %>
<%= f.fields_for :speaker, :remote => true, :html => {:data_type => 'html', :id => 'create_speaker_form'} do |g| %>
<%= g.label :name, "Or, add a new speaker:" %><br />
<%= g.text_field :name %>
<%= g.submit %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
probably your question has been answered here How do you submit a rails 3 form without refreshing the page?
if that doesn't help you can try using preventDefault() attaching it to your submit button.

Resources