simple_form collection checkboxes add unexpected values to database - ruby-on-rails-3

Environment: Rails 3.2.1
SimpleForm 2.0.1
I have encountered users here and elsewhere asking similar questions via Google, but I have not yet found answers!
I want to provide a series of checkboxes to define a contact's preferences.
I made a small test app using something I noticed on the simple_form demo app.
My Contact model has a string attribute named "post_pref"
In ContactsHelper I included this:
def contact_preference_options
['High Resolution','Web Resolution','Browser','Hard Copy Proof']
end
In my _form partial I include this:
<%= f.input :post_pref, :collection => contact_preference_options, :as => :check_boxes %>
I started the server and created a new Contact.
In the New and Edit views, the checkboxes show up. I checked "Browser" as a preference for my new Contact and submitted it.
The result of checking one or several preferences is a mess.
First:
when I go to edit a record, the current preferences aren't checked.
Second:
In the Show and Index views I see this:
--- - Browser - ''
In the console, I see this:
---\n- Browser\n- ''\n
What I want to see is this:
Browser
My questions are:
Where are the dashes coming from?
Where are the new lines coming from?
Why is there an empty string?
Why aren't the previously selected checkboxes checked when I edit a Contact?
Note: when I did the above with radio buttons or select options it works fine. But I want the contact to potentially have several preferences so I need checkboxes.
Interestingly, I tried the same thing with formtastic instead of simple_form and got almost identical results. What's the trick for checkboxes?
Thanks a million for any help.

For me it looked like it was saving the array, so I did some preprocessing of the parameters before saving it:
lifestyle = params[:lifestyle]
lifestyle[:languages] = lifestyle[:languages].reject(&:blank?).join(",")
if #lifestyle.update_attributes(lifestyle)
...
In this example, my checkboxes was languages under the lifestyle model. Hope this helps.

Related

I want to export searched data to excel file in rails app

I have implemented search option in my project. It searches records on basis of many fields given by user And then displays record according to it. Now I want those filtered records to be exported as excel. How can I do that?
You'll need to merge the search parameters. The parameter merging allows you to reuse whatever parameters were passed in the page and apply the xls format. Example below.
=link_to 'Export', users_path(request.parameters.merge({:format => :xls}))
(tested on Rails 5.0)
In my case, adding download: 'projects.xlsx' solved my problem!
<%= link_to 'Export',
projects_path(request.parameters.merge({format: :xlsx})),
download: 'projects.xlsx' %>
I have found a method where I can send params in download link.
So after the user submits the form and result is displayed url contains all the params of the form. So what I have done is that I have taken the current url(which contains all the search params) and append the format as xls to it. Example is given below -
This solution works fine for me

Rails ActiveRecord hash displayed on page

I am creating a sortable list of items from my database using the railscast found here: http://railscasts.com/episodes/228-sortable-table-columns
The sorting works fine, but when the page displays, it seems to print out some sort of hash above the table according to the number items. Each unit looks something like this:
#<ActiveRecord::Relation:0x00000006f9a500>
I've checked the html code and there is nothing in it that prints anything. Is this some sort of debug statement? How do I get it to stop printing?
You are printing object, but you need only one attribute.
Do something like this:
<%= your_object.YOUT_ATTRIBUTE %>

rails3 sort where clause issue

I followed a tutorial on rails3 sorting, not sure which one, and i got it working. I have a table, and depending on the button pushed, I wanted to be able to sort on one of the columns.
Here is an example of the buttons:
<%= link_to "Time", :sort => "transit_time" %>
The column looks like this:
<%= result.transit_time%>
(multiple times obviously)
In the controller, I originally did:
#results = Result.order(params[:sort])
And this worked.
However, now I have added a where clause to be able to query more specifically, so my query looks like this:
#results = Result.where("(NOT(train) OR :traincheckbox)AND . . . :end_location => params[:end_location]}).order(params[:sort])
THIS NO LONGER WORKS. The reason is because when I click the button, it reloads the page, and eliminates all the query string. When I first load the page the query string looks like this:
"http://localhost:3000/results?utf8=%E2%9C%93&start_address=24+Grosvenor+Square&start_l . . .etc."
and once I push one of the sort buttons it turns to this:
http://localhost:3000/results?sort=escore
All my results disappear because there is nothing in the query string, nothing to be passed into the WHERE clause.
ANY IDEA HOW TO KEEP THOSE PARAMS PRESENT?
Sorry that is long, but I'm a relative beginner at rails and I need help.
Thanks!
First of all, I would highly recommend you use the MetaWhere and MetaSearch Gem
One way you can keep the variables present in your next screen is to store them in hidden fields (of a form), then when you click sort, pass those hidden fields over to form your query.
Hope this helps!

Ruby on Rails 3: rails_admin + puret?

Did someone try to integrate puret into rails_admin? I can't make a language switch to edit different translations :(
Changing I18n.locale forces whole rails_admin to use specified locale.
Now I got the solution. The two can work together well. In short:
Delete the pureted column(s) in your model
If you have the column pureted still in your model, rails form helper will bypass puret. That is, if a model called Post has a field called contents to be i18ned, the table posts SHOULD NOT have the column contents.
Actually we should use globalize3 instead. With this you do not need to remove the original column. And puret doens't support nested attributes assignment. globalize3 works very well.

Complete noob Jquery / Rails setup question (probably)

Background: I've been doing RoR for about a year now, and am fairly comfortable with it, however, I know next to nothing about Javascript.
I've been playing around with some jquery autocomplete stuff in my rails app. I pretty much had a version working, but needed some tokenized fields too for a one to many relationship.
Right on cue - good old Ryan Bates does a railscast on it. So I start following the instructions.
Got a little bit nervous when I had to start installing 'jquery-rails' gem (I'd already installed jrails to get the other stuff working).
As suspected, it broke some stuff but I managed to get that working again.
Anyway, I got most of the way through the tutorial, and everything was going fine - I've got the tokenizer script to find the correct input field and it acts as expected. I've tested the json link too - that sends back all the right stuff.
However when I start typing in the text field - nothing happens, and when I view the console window it comes back with:
Uncaught TypeError: Cannot call method 'replace' of undefined
jQuery.jQuery.extend._Deferred.deferred.resolveWith
done
jQuery.ajaxTransport.send.callback
I can make guesses as to why this is going wrong - but any expert advice would be greatly appreciated.
(I should also add - I'm using formtastic too)
Thanks in advance.
Ok, finally figured it out.
It turns out that my author's name column is not name but rather author. So I needed to make a change inside the js.coffee script to override that default search of name.
The line you need to use is:
propertyToSearch: "author"
My whole book.js.coffee file now looks like this:
jQuery ->
$('#book_author_tokens').tokenInput '/authors.json'
theme: 'mac'
prePopulate: $('#book_author_tokens').data('load')
propertyToSearch: "author"
This actually fixed the error Uncaught TypeError: Cannot call method 'replace' of undefined
Of course, if you do use a different column name you will want to also edit the functions in the author.rb file to reflect that:
def self.tokens(query)
authors = where("author like ?", "%#{query}%")
if authors.empty?
[{id: "<<<#{query}>>>", author: "New: \"#{query}\""}]
else
authors
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(author: $1).id }
tokens.split(',')
end
Edit
Another thing I had to do for the fieldsto be prepopulated with the existing authors was change this:
= f.input :author_tokens, :data => { :load => #book.author }
To this:
= f.input :author_tokens, :input_html => { :data => { :load => #book.author } }
And then they would show up.
Hope this helps you.