Multiple Checkboxes, Convert to String, Single DB Column Rails - ruby-on-rails

I have a form, that among other things, contains about 20 different checkboxes. Like so:
<%= form_for #inventory do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
...
<p>
<%= f.check_box :apple %><%= f.label :apple %><br />
<%= f.check_box :banana %><%= f.label :banana %><br />
<%= f.check_box :orange %><%= f.label :orange %>
...
</p>
...
<% end %>
What I want to do is take the value of the selected checkbox, comma delimit them, and save them in a column in the db. So if the apple and orange checkbox is checked it saves as:
#inventory.fruit = "apple, orange"
how do I do this?

I don't think we can send multiple values as a string rather than an array. Look at the below solution
In Rails, how to handle multiple checked checkboxes, just split on the , or?
The solution is in pure HTML code but you can use check_box_tag instead.

Related

Hardcode partial input value in a Rails form_for field

I have a Rails form where the user is able to make a Top5 list. While they are able to label the list, all lists start with the phrase "Top 5 Greatest." Of course, it's easy to use Regex and append this phrase to the front of a list in the controller, but then I'm stuck doing it for both the create and update actions, so it's not very dry. Is there a way to hardcode a partial value in a rails form_for that will then be combined with the rest of the form input and sent to the controller?
This is currently what the form looks like (minus the form_for partial):
<br><%= f.label "Top Five Greatest:" %>
<%= f.text_field :title %><br>
<%= f.hidden_field :user_id, value: user.id %>
<br><%= f.label "#1" %>
<%= f.text_field :number1 %>
<br><%= f.label "#2" %>
<%= f.text_field :number2 %>
<br><%= f.label "#3" %>
<%= f.text_field :number3 %>
I'd really appreciate any insight.
Override setter method:
# put this in your model:
def title=(value)
super("Top 5 Greatest #{value}")
end

Rails creating multiple entries at once

I am trying to figure out the cleanest way to create multiple DB entries at once (or if it's even a good idea).
I have an Event model, which has many Bands and many Venues, through the event_bands and event_venues models.
Right now, the user first creates the event, then is redirected to the form to create the event_band and event_venue relationships. I would like to streamline all of this into one form if possible, like this (bottom lines are most relevant):
<%= form_for #event do |f| %>
<%= f.label :name %>
<%= f.text_field :name %><br />
<%= f.label :contact %>
<%= f.text_field :contact %><br />
<%= f.label :price %>
<%= f.text_field :price %><br />
<%= f.label :info %>
<%= f.text_area :info %><br />
<%= f.label :date %>
<%= f.date_select :date, start_year: 2014 %><br />
<%= f.label :time %>
<%= f.text_field :time, placeholder: "7:40pm" %><br />
<%= f.label :band %>
<%= select(:event_band, :band_id, options_for_select(Band.order(name: :asc).collect { |b| [b.name, b.id]} )) %><br />
<%= f.label :venue %>
<%= select(:event_venue, :venue_id, options_for_select(Venue.order(name: :asc).collect { |v| [v.name, v.id]} )) %><br />
<%= f.submit %>
<% end %>
Because the event_band and event_model require event.id, I guess I would have to use an after_create callback to build and save them. The issue I'm having conceptualizing this is that I want to post those extra :band_id and :venue_id params through the form for the event.
Is there a cleaner way to handle posting params for multiple models through one form and then using them in a callback or am I headed in the wrong direction?
You can use fields_for : see doc

Can't seem to pass variable using select_tag

I have a form in Rails that I need to create an option tag in HTML. It's a pretty simple option list with static values. I could create it in HTML easy enough, but I want to do it the "Rails Way"
Here is a portion of my form:
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone %>
</div>
<div class="field">
<%= f.label :area %><br />
<%= select_tag "area", options_for_select([["Northeast", "NE"], ["Southeast", "SE"], ["Central", "CE"], ["West", "WE"], ]) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
When I use the select_tag, my form shows that it is successfully posting changes, but the value that is passed by the select_tag is not updated to the database. I have verified that a simple text field DOES pass the value.
I'm sure I'm missing something very simple, but I'm having a difficult time identifying it. Please help. Thanks!
Rails Newbie
Check your rendering: a bare select_tag will render "area" as the name/id, whereas everything else in your form will have a normal model-based name.
For example, if the model was "user", the phone field's name would be "user[phone]".
You can see this happening by looking at your parameters passed to the action in the log.
Either use the form helper, or name it correctly the same as the other fields.
See also: select, select_tag, select (not helpful), and form helpers. The "Understanding Parameter Naming Conventions" section might also be of interest.
select_tag is like text_field_tag: it doesn't cooperate with the form builder (the object form_for yields) in order to get the proper parameter name and current value.
the select helper is ever so slightly different to select_tag in that it calls options for select for you, so you only need to write
f.select 'area', [["Notheast", "NE"], ...]

How to create only the field_for object in a nested form

I have a nested form where users can create any amount of products (<%= f.fields_for :products do |product| %>) and at the same time also create a location (nested_form_for #location) to put those products. But instead, what i want is users to select a location and only be allowed to create the products. I don't want to create the locations at all on this form. The form also should not give a location per product but only one location for all of them.
How would you make the form select a location and create products only ?
This form creates both the location and X amount of products:
<%= nested_form_for #location, :validate => true do |f| %>
# This will turn into selecting of predefined locations and not creating
# the location as you see below this line
<%= f.label :business_name, "Business Name" %><br />
<%= f.text_field :business_name %>
<%= f.label :address %><br />
<%= f.text_field :address %>
<%= f.label :phone_number, "Phone Number" %><br />
<%= f.text_field :phone_number %>
<%= f.label :website %><br />
<%= f.text_field :website %>
</div>
<%= f.fields_for :products do |product| %>
<%= product.label :name %>:<br>
<%= product.text_field :name %>
<%= product.label :price %>:<br>
<%= product.text_field :price %>
<%= product.link_to_remove "Remove" %> # Removes a product field
<% end %>
</div>
<p><%= f.link_to_add "Add Product", :products %></p> # Ajax add product field
<div class="actions">
<%= f.submit %>
</div>
<% end %>
If I understand you correctly, you want users to choose from a list of locations, and then add products to that location. These locations are predefined somewhere (I'm getting in your db_seed) in your application. Assuming those two things, then the question to your answer is just have a normal form_for #product and inside your form you will have a select with the option objects being the location where they users can choose.
<%= form_for #product do |p| %>
<%= p.label :name %>:<br>
<%= p.text_field :name %>
<%= p.label :price %>:<br>
<%= p.text_field :price %>
<%= select :product, :location_id, Location.all.collect {|l| [ l.business_name, l.id ] } %>
<% end %>
and in your controller you can just get the location with params[:product][:location_id] to retrieve the location the user selected and do your normal database stuff. Hopefully that's clear enough for you.
If you want to create more than one product at a time, you need to use a form_tag and generate your own helpers to add/remove products. This is more difficult but creates a better user experience.

Drop Down Box - Populated with data from another table in a form - Ruby on Rails

I am attempting to add a note capability to my CRM that I am creating.I am employing an authenticated environment where users can manage their prospects. For instance, I sign up, I login, I can enter prospects and view them. So...I have created a prospects and user table and have them all working great. I am now trying to give the users the ability to take a note and "attach" it to a prospect. So...I have created a notes table with the columns, note & prospect. The user can take a note from wherever they pull this form, and my goal is to have their clients names available in a dropdown box to attach to the form. So far I have created an object in the prospects controller that says the following
def index
#myprospects = current_user.prospects.find(params[:id])
end
I am struggling with the next step to create the dropdown in the view/notes/new.html.erb file. The form looks like this:
<h1>New note</h1><hr/>
<% form_for(#note) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :note %><br />
<%= f.text_area :note %>
</p>
<p>
<%= f.label :prospect %><br />
<%= f.text_field :prospect %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', notes_path %>
How do I map the
<p>
<%= f.label :prospect %><br />
<%= f.text_field :prospect %>
</p>
field to display the data I want? I am three days into rails so talk to me like I am a 10 year old (a 10 year old that doesn't know rails).
You're looking for a select box.
Rails provides a lot of helpers to create form inputs. The right one for your job is collection_select.
Assuming you've set up a many-to-one relationship between notes and prospects properly, and the column that contains a prospect's name in the prospects table is called 'name', this will do exactly what you want:
<p>
<%= f.label :prospect %><br />
<%= f.collection_select :prospect_id, #myprospects, :id, :name, :prompt => "Select a prospect" %>
</p>

Resources