How to create checkboxes using scaffold in rails? - ruby-on-rails

I have to create a feature to manage my contracts. Everything was going fine working with the strings etc.. but I have to create checkboxes in my scaffold for an example
()Toll
()Chemist
And I want to save this if the boxes are checked.
I tried put this code into the Form file, it appears, but don't save the data when checked, I guess that is not the correct way, because there is nothing created in the database.
<input type="checkbox" name="tag_ids[]" value="1" />
I'm planning to generate all the checkboxes as strings when generating the scaffold and try something else.
Does anyone have a better idea how can I accomplish this, could be the easiest way as possible is not for real development. Thanks for all.

first you should check if the vars are whitelisted,
second you should try the rails helper for this:
<%= form.check_box "tag_ids[]", "Chemist", false, id:"1"%>
with this syntax the input will be stored in an array, so you can add multiple checkboxes for the same variable. the input will than be stored ["Chemist","Toll"]
Later you can split these easily by .split

You can add the following to your form
<% Tag.all.each do |tag| %>
<label>
<%= f.check_box_tag "contract[tag_ids][]", tag.id, #contract.tags.include?(tag) %>
<%= tag.name %>
</label>
<% end %>
This can then be passed through your parameters as long as your strong parameters allow them eg:
params.require(:contract).permit(.... , tag_ids: [])
see here for a proper discussion: https://kolosek.com/rails-join-table/
Also if you are interested I'd look at using simple_form (https://github.com/plataformatec/simple_form) for your rails forms. It makes all of this really easy.

Related

How to tell options_for_select field where to save selected option value?

I'm returning to Rails after almost 5 years away and building out a personal project. In my _form.html.erb file, I'm trying to use a field, but the data never gets saved where I think it will be.
<select>
<%= options_for_select([['black'], ['blue'], ['red']], :selected => :color) %>
</select>
In my index, when I try to use model.color I get nothing returned. I'm sure its something basic I'm not getting, but for some reason Google searches and example code doesn't look like exactly like what I got. I'm not sure what option to pass to tell the form where to save the selected value.
You need to give the select tag a name (e.g. <select name="foo"> populates params[:foo], <select name="foo[bar]"> populates params[:foo][:bar]; alternatively use the select_tag/select form helper methods – see https://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag and https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-select).
Be aware: If you haven't used Rails for several years, chances are you don't know about strong parameters which you need to use if you want to do direct assignment (e.g. User.new(params[:user]) doesn't work as it used to in older Rails versions – you need to use strong parameters here). Details: https://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters.
You need to assign the input a name in order to do anything meaningful with it - This is not Rails specific. Its universally true for web development. Form data in HTTP is just a bunch of key value pairs and the name attribute sets the key.
In Rails you should use the form builders and input helpers unless you have a very good reason not to - it is after driven by convention over configuration. They will handle assigning the name attribute for you:
<%= form_with(model: #thing) do |f| %>
<%= f.select :color, [['Black','black'], ['Blue','blue'], ['Red', 'red']] %>
# ...
<% end %>
This renders something like:
<select name="things[color]">
<option value="black">Black</option>
# ...
</select>
And would give you the following params hash:
{
thing: {
color: 'black'
}
}
They also provide data bindings between your model and the form so that the inputs are not reset when the user submits an invalid form.
I would really start by reading the rails guides as you have a lot to catch up on.

Rails Select Link

I'm new at this and have searched but haven't been able to find the exact combo of answers I'm looking for. I'm trying to create a pull down menu which will be supplied by a database column (my code works up to here) and then have each option be a link which will go to the page for the selected city.
<%= collection_select(:city_id, 0, City.visible, :id, :name) %>
The line above creates the pull down I need filled from my City db column.
Can I then add a link_to in here somewhere? I've seen people talk about jquery but doesn't Rails have an answer for this? I'd like the link to go to city/cityName.
Thanks for any help!
Edit - The other link provided doesn't exactly show the data pulled in from the database.
While there might be a way to use rails link_to, I've ended up using html_safe in these situations. Have you tried replacing the "text" value of your collection via html_safe? such as:
"<a href=#{show_path_for_object_here}>#{text_of_object_erb here}</a>".html_safe
If your routes for cities are standard like:
resources :cities
Then the actual code will probably be fairly close to:
<%= collection_select(:city_id, 0, City.visible, :id, "<a href=cities/#{city.id}>#{city.name}</a>".html_safe) %>
I finally found a way that works perfectly. I did end up needing to use a bit of JavaScript and forego the Rails select tag. Either way, I wanted to post what worked really well for me:
<select onchange="window.location=this.value">
<option>Select a City</option>
<% #cities.each do |c| %>
<option value="city/<%= c.permalink %>"><%= c.name %></option>
<% end %>
</select>

Manually Creating Form Fields in Rails, How does rails auto populate fields when editing?

I am creating a form in Rails by hand, ie:
<input type="number" name="funds_application[product_revenues_attributes][1][amount]">
This works fine when submitting data, but when I am editing a record the fields do not auto populate. Does anyone know how rails does this? Do I need to use a <%= text_field_tag %> to get that part of it working.
This is a small part of a larger form where I am using Simple_form, and the rest works as expected. I find complex forms sort of mind melting in rails, what does it want?
Do you have to do it by hand? Can you still use form helpers?
Anyways, the way Rails does it is that you always give the form an instance of the model you are working with, and call the getter on its attributes. For a new instance, they'll be blank. For a saved instance, they'll have values. For instance, if you had a User model with a login and name attribute, you could do #user = User.new in your controller, and in your form do (using helper tags):
<%= text_field_tag "login", #user.login %>
<%= text_field_tag "name", #user.name %>
And if you had an actual user (#user = User.first), you could still use it with that view.
So no, you don't have to use the form tags, because the underlying principle is always giving an instance of the model you are working with, and deciding what defaults to use if an attribute is nil/blank.
So if you always had an object to work with, and yet still wanted to do it manually, you could type:
<input type="number" name="funds_application[product_revenues_attributes][1][amount]" value=#my_object.amount>
Or whatever the field really is. That way, it gets some default value, but if the object already has something for that attribute, it will output it.
If you're building the form yourself, you can populate the fields yourself from the object passed in, with code along these lines:
<input type="number" name="funds_application[product_revenues_attributes][1][amount]" value="<%= #model.value %>">
The most railsy way to do it is with the form_for construct, though. The guide on this is pretty good.

Maintaining the nested levels while serializing a field generated using fields_for

Thanks to help from people earlier, I am getting a hang of how to serialize a nested hash into a single column. While I was able to generate the form fields at multiple levels and get values of the fields back in to a string, I am unable to retain the different levels for the hash.
My hash looks like the following:
My code looks like:
<% categoryvalue.each do |categoryproperty, categorypropertyvalue| %>
<div>
<%= f.fields_for :categories, categoryproperty do |categoryattribs| %>
<%= categoryattribs.label categoryproperty %> <br/>
<%= categoryattribs.text_field categoryproperty, :value => categorypropertyvalue %> <br/>
<% end %>
</div>
<% end %>
The final hash string in my example takes data for two categories and must look similar to the following string when it gets assigned to :categories should look like the following:
{"0" => {"Active"=>"yes", "totalproducts"=>"100", "segment"=>"Premium"}, "1" => "Active"=>"yes", "totalproducts"=>"190"}}
However, the string is coming in the following form:
{"Active"=>"yes", "totalproducts"=>"100", "segment"=>"Premium", "Active"=>"yes", "totalproducts"=>"190"}
Is there a way to differentiate the attributes of one category from another and have two separate hashes within the main hash? Right now everything gets flattened out to a single level. This is evident in how the id and names for input fields are generated. See the sample below:
<input id="product_categories_Active" name="product[categories][Active]" size="30" type="text" value="%" />
<input id="product_categories_Active" name="product[categories][Active]" size="30" type="text" value="lbs" />
What I actually want is product[categories][0][Active] and product[categories][1][Active].
Any suggestions on how to approach this?
Just in case someone stumbles on this question having a similar problem, I wanted to share the final solution.
You have to use text_field_tag, select_tag etc. instead of the fields_for helper. Use a loop (.each_with_index do |key, index|) to iterate through your hash. Then basically generate a fully qualified name for each field in the format "product_categories_0_active".
I will try to write a tutorial or blog on this once I am out of the woods on my project but I think most people will figure it out from here.
Hope it helps.

Ruby on Rails Forms: how to create a CheckBox Table (or List)

What's the best way to create a related set of checkboxes in Ruby on Rails? In the ToscaWidgets library used by Turbogears you can do the following:
twf.CheckBoxTable('arbitrary_numbers',
num_cols=5,
options=['1','2','3','4','5','6','7','8','9','10']),
This generates 10 labeled checkboxes in two rows of 5 checkboxes. I'm trying to duplicate this in Rails without just creating 10 separate checkbox controls. No big deal, just hoping for a clean way to do this.
Something like this:
<% 10.times do |i| %>
<%= label_tag i %>:
<%= check_box_tag "alternate_numbers[#{i}]" %> <br />
<% end %>
will produce 10 checkboxes and if you will put it into form and submit it, you will have access to it in params[:alternate_numbers][index] where number is your number. You can put it into helper and call many times. You can also add some parameters to helper to customize output.

Resources