rails bringing back all checkboxes instead of only selected one - ruby-on-rails

I am using simple_form and have a following sample tag:
<%= f.input :medical_conditions, :label=>false, :collection => medical_conditons, :as => :check_boxes%>
The collection holds about 100 checkboxes. However, when user only selects 1 or 2, everything is still getting saved to the database like this:
---
- ""
- ""
- ""
medical_conditions is a simple array in my application_helper
def medical_conditons
t = [
"Allergies/Hay Fever",
"Diabetes",
"Heart Surgery"]
return t
end
the medical_conditions field is a :string field.
What do I need to do so that only values that are selected are saved in comma separated manner.

It is not simple_form behavior. It is from Rails. See this: http://d.pr/6O2S

Try something like this in your controller (guessing at how you wrote your create/update methods)...
params[:medical_conditions].delete('') #this will remove the empty strings
#instance.update_attribute(:medical_conditions, params[:medical_conditions].join(','))
#or however you want to save the input, but the key is the .join(',') which will
#create a comma-separated string of only the selected values, which is exactly
#what you're looking for me thinks :-)
If that does the trick for you, I'd consider making a private helper method that formats the params for you so that you can use it in #create, #update, or wherever else you need it. This should keep things a little cleaner and more "rails way-ish" in your crud actions.

Related

Getting Globalize and autocomplete to work together

Using globalize gem to manage translations with autocomplete, there is a situation where a number of hooks need to be properly set. Note: this does not use hstore AFAIK. I have not managed to find a way to do so. The most productive set-up to date has
controller:
autocomplete :nation, :name, :full => true
Nation
translates :name
view
<%= autocomplete_field_tag 'nation_name', '', autocomplete_nation_name_itins_path, size: 35, :id_element => 'nation_id' %>
There is no inherent reference to nation_translations database table created by Globalize as of yet. As this image suggests, there is a problem:
Issue 1: The input remains binded to the base table's attribute value (I have not yet cleared them out as the Globalize gem suggests. Otherwise I'd be getting blanks). can is actually ready all values of canin master table... Typing in other locales, like cyrillic say Канада has naturally no effect as that value is not part of the Nation table.
What is interesting is that the drop-down values are being populated by Rails automatically, extracting the translation values of what is input.
Issue 2: I'd rather pass the parameter 'nation_id' which is naturally part of the nation_translations table with the form data. although I can append , :extra_data => [:nation_id] to the controller it is not being submitted (example in cyrillic where the input is given without any autocomplete)
{"utf8"=>"✓", "nation_name"=>"Канада", "commit"=>"..."}
Rails.logger.info :extra_data returns:
extra_data
Now the second issue can be overcome because a query like
Nation::Translation.where('name = ?', "Канада").pluck('nation_id')
returns a proper result. But that point is moot if the autocomplete is not playing ball with the user's input.
How can this be configured to have user input autocomplete with the current local translations?
this does get solved by creating an entirely new class with attributes nation_id, name, locale and can thus be called symbolically.
The query call is not that straightforward however. As the gem suggests, the method need to be tweaked
def autocomplete_nation_name
term = params[:term].downcase
locale = params[:locale]
nationtranslations = Nationtranslation.where('locale = ? AND name LIKE ?', locale, "%#{term}%").order(:name).all
render :json => nationtranslations.map { |nationtranslation| {:id => nationtranslation.id, :label => nationtranslation.name, :value => nationetranslation.name} }
end
intervening on the action method itself provides all the leeway desired...

How to add a search parameter to an existing Ransack query

I have a search form on a page, that allows a user to filter a list on multiple conditions. Now I'd like to add quick links on top of the list to apply scopes. I tried it like this:
= link_to "Visited", q: {"activated" => true}
While this filters the list to show only activated items, it also resets the search query. In other words, it doesn't remember what was already filtered in the form.
Is there a way to adapt #q so that I can add this "activated" => true to the hash of required filters?
Assuming you're only using the :q param to filter, you could aggregate that.
= link_to "Visited", q: (params[:q] || {}).merge(activated: true)
I don't think you can because if you follow a link you are not submitting the form therefore the parameters are not going to be submitted.
Passing the params in your link to will send the params if any exist:
= link_to "Visited", q: {"activated" => true, "your_params" => params}
This will only work if the form has been submitted once though, otherwise the params would be empty.
EDIT
I assume that the fields on your forms are populating if there is a value.
For example,
<%= text_field_tag(:email, if !params["email"].nil? then params["ip_email"] end) %>

rails association populate field from another table

Hoping this will be a straight forward question, but is anyone able to let me know the best way of populating a hidden field based on a value on another table.
I currently have 2 tables - table_numbers which has the following fields - id and value(decimal), and table_records which has an amount field.
On the form to add a new record I have the following to add a value to it
= f.association :table_number, :collection => table_numbers.order('value ASC'), :label_method => :value, :prompt => "Select a value", :label => "value"
At the moment this is populating the number_id on the records table, but displaying the value on the form when adding a record. What I would like is to get the value as well to be able to run a calculation on the value and amount.
What would be the best way to do this? Update the line above or do I need to add extra code?
Thanks
You can perfom calucaltions in before_save callback in model. If you want to display calculations, use helper and show it.

How do I use a check_box_tag for value that isn't a boolean?

I have a field in my database called property_types which has a string value and the values can be "Condo" or "Single Family Home" or "Commercial". I want to display each property type in the user's search form with a check box next to each property type so the user can select which property types should be included in their search results.
But if the property_type field is not a boolean and it has several possible values how do I do this using check_box_tag which can only have a true or false value?
EDIT:
I added this checkbox code to properties/index where the search form is and the search results are displayed:
<%= check_box_tag(:condo, value = "1", checked = true) %>
In properties_controller I added this:
#properties = #properties.where(:property_type => "Condo") if params[:condo].present?
Ofcourse it doesn't work because I haven't got a clue what I'm doing but is this along the right lines or not?
Well, looking at you requirements i would suggest you to leave the values at true and false, and on your controller, when you persist the object, you check all possibilities that are checked (true) and put you project_types attribute together.
project_types += 'condo&' if params[:condo]
project_types += 'commercial&' if params[:commercial]
...
Of course the & i put in the examples are just for demonstration, as i don't know how you would create this string.
EDIT:
Well, maybe you should refactor your model. I believe it would be easier if the project_types attribute didn't exist, and instead, you had several boolean attributes named after your strings. Then you can search like this:
#properties.where(:condo => params[:condo], :commercial => params[:commercial])
And it would be easier to understand the code.

Rails select helper - set default?

Rails 2.3.11
I did read this answer, but it's not working for me.
I would like the default option for this selection box to be the event_id passed through the URL.
f.select :event_id, #events, :selected => url_args["event_id"]
An example #events is[["SC 2 Tournament", 195], ["Obstacle Course", 196], ["Mortal Combat", 197]]
The following also didn't work:
adding ".to_i" to "url_args["event_id"
using options_for_select(#events, url_args["event_id"]
Thank you!
This is a lot easier if you use the collection_select helper:
f.collection_select :event_id, #events, :id, :name
Then to select the default option (and have that be selected on pageload), you can simply assign it to whatever Object it is that the form is for within the controller. eg like this:
def new
#events = Event.all
#thing = Thing.new(:event => #events.first)
end
I'm not sure where your url_args comes from, but I'm guessing it's probably from a param in the URL, in which case you can do this:
Thing.new(:event_id => params[:event_id])
One last thing - collection_select won't quite work with #events as you've specified it, as you're using a nested Array, when it's expecting an Array of Objects that it can call id and name on in order to retrieve the values and display text for the select options. To fix that, simply redefine #events within your controller, using one of the ActiveRecord finders, such as Event.all or Event.find(..).
Make sense?

Resources