Use time_zone with best_in_place - ruby-on-rails-3

I'm using time zones in my app, and can happily use the built in Rails 3 help method to have a collection of time zones when using a standard form, or even a simple_form.
However, best_in_place needs to have a collection presented to it. Does anyone know how to get the list of time zones so that they can be presented as a collection to best_in_place?
I've been trying something on the lines of the following:
best_in_place #account, :time_zone, type: :select, collection: ActiveSupport::TimeZone.all { |e| [e.name] }
However, I always seem to get a list but with blank lines. The above was the closest in that BIP takes the value, but it is still empty.

Related

rails form fields_for serialize hash

I need to create a check list for a comment form on which users to notify about a comment.
I have a comment model and i have a column called comment_meta which i want to store as a serialize hash.
My comment form has a fields_for comment_meta example;
<%= f.fields_for :comment_meta do |comment_form| %>
<%= comment_form.check_box(contact.id) %>
<% end %>
The params being passed are "comment_meta"=>{"155"=>"0", "156"=>"1", "157"=>"0"}},
but my db is saving an empty hash.
The field type for comment_meta is a text.
Is there a way to save this?
Your comment_meta hash seems to be a 'key-value pair' of ids and Boolean values, respectively. If this is true, then you may be better off going with a users_comment_metas 'through' table.
You would benefit from restructuring to this methodology because:
db indexing is fast - rails hash serialization/parsing to and from the db is slow (unless your using postgres's h-store, but thats another story)
Dynamic reporting about all data in your db will be much more intuitive/query-able as a developer attempting to display readable reports (which is very important at my job at least).
Your goal of using Rails' built in form helpers will be much easier.
If you truly want to go the hash route you've suggested, there could be a variety of things preventing it from saving. Here's how I would troubleshoot:
First make sure you have the line 'serialize comment_meta, Hash' in your Comment model.
Remove ALL validations you may have in the Comment model for testing purposes.
Now, type 'debugger' (no quotes) in your controller create and/or update
action in your comments_controller (or the controller you are
requesting from the form)
when you hit your debugger statement in your terminal, type the words
'eval comment_params' to check the comment params you've submitted (I am assuming you are using the strong parameters gem, seeing as you typed 'ruby-on-rails-4' in your tags for this post).
The hash should have this structure as you've suggested above (if it looks different,
something is wrong in your form, or you have strong paramters set up incorrectly, more info here):
"comment_meta"=>{"155"=>"0", "156"=>"1", "157"=>"0"}
type 'n' until you've passed the line initializing a new object with the params
#comment = Comment.new(comment_params)
Now type 'eval #comment' to see your new object, and then type 'eval #comment.comment_meta' to see if the hash is being stored. If it's returning nil, then type 'eval #comment.valid?'. If it returns true, then type #comment.errors to see what is wrong, and fix accordingly.
If all else fails, make sure you can do a manual assignment of any given hash to comment_meta of a new Comment object in your rails console:
#comment = Comment.new()
#comment.comment_meta = {"test"=>"1"}
#comment.save!
I hope this gets you on the right track.

Rails Displaying Flash Messages from Model

I'm trying to display some error messages from my model in Rails. Currently, when an exception is caught in my test model and raised, the messages are returned as expected in the errors scope of my object. The messages are returned as follows:
{:key1=>["Your key needs to be different."],
:key2=>["Another exception"]}
This is perfect, as the correct exceptions are being thrown for the correct errors. What I'm trying to do now is bind these messages to the flash scope so that I can display them on my view. In my controller, when I have an exception, I then bind it to the flash[:error] scope as follows:
flash[:error] = #test.errors.messages
render :new
Upon doing this, my errors are bound to the flash scope, but when I output them on my view, they are displayed as follows:
[:error, {:key1=>["Your key needs to be different."], :key2=>["Another exception"]}]
All I'd like to do is display each one of these messages so that they look to be like:
Your key needs to be different.
Another exception.
Notice that in the above example, all that will be rendered is the message text.
Will you please point me in the right direction as to what I need to change either in my controller or in my view to achieve the desired output above?
Thank you in advance.
The one place I immediately see for improvement is in the hash you're passing.
If there's not a specific reason you're wrapping your strings in an array, you can eliminate the array:
{
:key1 => "Somebody poisoned the watering hole!",
:key2 => "There's a snake in my boot."
}
That will both simplify your code and eliminate the two-dimensional array you didn't seem to be intending to create.
If there is a reason you're wrapping your strings in an array (multiple messages per key?), you'll need to revisit your iterator; the way it's written now, it's only going to display the first string for any given key.
I noticed that when I looped over #test.errors.messages in the following construct, I ended up with a 2-Dimensional array:
[:key1, ["Your key needs to be different."]]
[:key2, ["Another exception"]]
Since this is a multidimensional array, I was able to then simply loop over the array in my erb and get the value to display as requested in my question:
<% for i in flash[:error] %>
<%= i[1].first %><br />
<% end %>
Returns on the screen:
Your key needs to be different.
Another exception.
I'm always open to suggestions, so if there's a better way to handle this, then please advise! Otherwise, this does work for me.

simple_form collection checkboxes add unexpected values to database

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.

Best way to hook into a Rails 3 page lifecycle

I have the following scenario: I am adapting a edit in place library to be able to display formatted values after the value is edited on an input field.
For that, I want to store the id for some fields being rendered on a given controller action to be served via AJAX whenever needed.
I want to be able to do the following in a view:
<%= edit_in_place #object, :attribute do |value|
"Formatted display value is #{value}"
end
%>
So, I generate a UUID for the control being rendered:
<input ... data-uuid="27b52850-d68f-012e-5dc8-28373723e63c" ...>
The ultimate goal is to keep a FormattingRules hash that would take the block being passed and assign it to the UUID so I could later on, after the user has edited the value, call an AJAX method to format the value:
http://server/format/27b52850-d68f-012e-5dc8-28373723e63c?value=My+Value
The following code is triggered:
def show
block = BestInPlace::FormattingRules[params[:id]]
render :text => block.call(params[:value])
end
And the cod returns:
Formatted display value is My Value
Which is great. With this, I can hide the edit in place input and display the formatted value.
Everything works already, however the FormattingRules hash is growing indefinitely and never being emptied.
My question is: is there a way I can hook into the Rails lifecycle and make this hash more granular (per page or session, maybe?) and make sure it's gone after the page is no longer being used?

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!