Complete noob Jquery / Rails setup question (probably) - ruby-on-rails-3

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.

Related

Texticle in rails isn't providing the responses I want. How configurable is it? or have I got it wrong?

I'm using the texticle gem in a Rails 3 app.
I've got a table full of food names, such as Onion, Green Onion, Onion Powder, etc. etc.
I'm searching the table with
foodnames = FoodName.search(params[:search])
return render :json => foodnames
when I attempt to search for 'chopped onion', I had hoped to get back a list of matching 'onion', as those are somewhat close, but I'm getting an empty set.
If I use just 'Onion' or 'Onions', I get back the list I expected.
there seem to be conflicting documentation with texticle.
the github repository page, https://github.com/texticle/texticle shows methods like fuzzy_search, but when I try to run that I get undefined methodfuzzy_search' for #Class`
the other documentation http://texticle.github.com/texticle/ says nothing about fuzzy_search or similar capabilities.
my gem file has gem 'texticle', '~> 2.0', require: 'texticle/rails', though I did add that in and re-bundle install after I original had it without the version or require statements.
can anybody clarify what is going on here, and how I can get a better search result? It seems far too strict for my needs as is, and I suspect things are not working as they are supposed to.

Rails 3 console and db:console are different

I have a rails app and when I have both the console and db:console open, they have different values for what is supposed to be the same field. I am using the send function to change the value. Here is the method in the model:
def toggle_approve(field)
self.send(field)
if(self.send(field).blank?)
self.send(field + '=', "new_value")
puts self.send(field)
else
self.send(req + '=', "")
end
rank.save
end
In my db:console (sqllite) everything is always correct, but in my regular erb console it is wrong. My view will then show what is in the erb console and not the sqllite. I dont understand what is going on in the background that would causing this issue. Any help would be great.
It's hard to be sure from the details you provided, but I think it is the case that your view uses an obsolete version of the data. Try calling .reload on the updated record, just at the point after the update and before presentation. See if that fixes your problem.

Dashes in property name not getting NoMethodError

I'm using the Linkedin gem to pull profile information for RoR 3.
Gem: https://github.com/pengwynn/linkedin
API Doc: https://developer.linkedin.com/documents/profile-fields#positions
Everything works except when I get to a property with a dash in the name.
<%=position.title %> displays correctly but<%= position.start-date %> return a NoMethodError in Users#show - undefined method start.
I've tried different operations like "startDate", "start_date", quotes around "start-date" but none have worked.
Is there a proper way to escape the dash/hyphen in the property name?
The expression in your ERB will be parsed as subtracting the value of the date variable from the result of a call to the start() method of the position object. Hyphens aren't valid in identifiers within Ruby.
I'm not familiar enough with the LinkedIn gem to suggest a solution, except to say that since it's based on an XML API, you should look for a way to manually pull data out of a tag pair. Most similar gems offer such a method. Also, this is a great case for using IRB as an exploratory tool: fire up an IRB session and see what happens when you call position.methods, after properly creating the position variable of course. My guess would be that you'll see something in that list which suggests an answer.
Looks like it returns a Hashie::Mash which converts keys, with a few extra rules:
https://github.com/pengwynn/linkedin/blob/master/lib/linked_in/mash.rb
You said you'd already tried position.start_date right? That should work. But if not, have you tried position['start-date'] or position['start_date'] one of those two should also work, since it's a Mash.

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.

Can you remove the _snowman in Rails 3?

I'm building an app on Rails 3 RC. I understand the point behind the _snowman param (http://railssnowman.info/)...however, I have a search form which makes a GET request to the index. Therefore, submitting the form is creating the following query string:
?_snowman=☃&search=Box
I don't know that supporting UTF encoding is as important as a clean query string for this particular form. (Perhaps I'm just too much of a perfectionist...hehe) Is there some way to remove the _snowman param for just this form? I'd rather not convert the form to a POST request to hide the snowman, but I'd also prefer it not be in my query string. Any thoughts?
You can avoid the snowman (now a checkmark) in Rails 3 by.... not using Rails for the search form. Instead of using form_tag, write your own as outlined in:
Rails 3 UTF-8 query string showing up in URL?
Rails helpers are great unless they're not helping. Do-it-yourself is good as long as you understand the consequences, and are willing to maintain it in the future.
I believe the snowman has to be sent over the wire to ensure your data is being encoded properly, which means you can't really remove the snowman input from forms. Since, it's being sent in your GET request, it will have to be appended to the URL.
I suppose you could write some javascript to clean up the URL once the search page loads, or you could setup a redirect to the equivalent URL minus the snowman. Both options don't really feel right to me.
Also, it doesn't seem there is any way to configure Rails to not output it. If you really wanted to get rid of it, you could comment out those lines in Rails' source (the committed patches at the bottom of railssnowman.info should lead you to the files and line numbers). This adds some maintenance chores for you when you upgrade Rails. Perhaps you can submit a patch to be able to turn this off?
EDIT: Looks like they just switched it to what looks like a checkmark instead of a snowman.
EDIT: Oops, back to a snowman.
In Rails 4.1 you can use the option :enforce_utf8 => false to disable utf8 input tag.
However I want to use this in Rails 3, so I monkey-patched my Rails. I put the following in the config/initializers directory.
# allow removing utf8 using enforce_utf8, remove after Rails 4.1
module ActionView
module Helpers
module FormTagHelper
def extra_tags_for_form(html_options)
authenticity_token = html_options.delete("authenticity_token")
method = html_options.delete("method").to_s
method_tag = case method
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
html_options["method"] = "get"
''
when /^post$/i, "", nil
html_options["method"] = "post"
token_tag(authenticity_token)
else
html_options["method"] = "post"
tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token)
end
enforce_utf8 = html_options.delete("enforce_utf8") { true }
tags = (enforce_utf8 ? utf8_enforcer_tag : ''.html_safe) << method_tag
content_tag(:div, tags, :style => 'margin:0;padding:0;display:inline')
end
end
end
end