I've searched a little about some ways to add a second field after States, to set a City based on it. I saw two options first : observe_field (From prototype) and jQuery, both with a select box. The fact is that I don't know JavaScript, and am in a hurry to set this... Well, I thought a text field with auto completion would be better, and maybe easiest to do.
Here we go : I have an model Uf and City, and both is populated with data. City has a "belongs_to Uf". The question is : How can I set something like this? Is there a way to do this with only ruby and rails?
To do this you'll want to have an AJAX action that responds to some search string query sent each time the user enters text. This action would respond to the view with data containing the result set of the search.
Here's a very simple example:
City Controller:
def search
term = params[:term]
cities = City.where('name LIKE ? OR code LIKE ?', "%#{term}%", "%#{term}%").order(:name)
render json: cities.map { |city|
{
id: city.id,
label: city.inspect,
value: city.full_name
}
}
end
Upon receiving a response, the dropdown would be populated with the results of the search. Selecting a value would set the field and store the matching id for the city in a hidden field for when the form is submitted.
I'd consider exploring the jQuery autocomplete Gem. If you're using Rails, there's a full-stack version here https://github.com/bigtunacan/rails-jquery-autocomplete which should be good to learn from.
Related
I am building a rails form and have an interesting problem I am trying to solve. I can't seem to find anything online to point me in the right direction. Thank you.
Is it possible to use a dropdown menu to select the :object_name for a text field?
In my head, I am picturing a collection_select form helper nested within a text_field form helper, though not sure this is possible.
In the form, I'd like the user to select the proper :object_name from an array
[:object_1, :object_2, :object_3, :object_4]
then give that entry a value with the text field
text_field(object_name, method, options = {})
The objects are all db columns in the same model.
Yes you can do that using jquery.
On change of the object names dropdown value, change the name attribute of the text field.
$('#selectObjectName').change(function(){
var field = document.getElementById("id-of-the-text-field-to-be-changed");
field.setAttribute("name", "value-came-from-the-selected-dropdown");
})
I feel like this is basic but can't find details anywhere.
I have a basic application created by generating scaffold.
There is form already built into this that enters data. I have a SELECT (drop down) box in the form. I would like to be able to have the OPTIONS in this select box be pulled from a database. Ideally, the end user would be able to add and edit these options.
I have no idea how to link that SELECT field in my form to where the OPTIONS will be STORED.
Can someone point me in the right direction as far as terminology as what to research? I'm coming up blank. I feel like this must be a common thing to do..
As ByScripts' link includes, here is the script that worked for me (for those where time is not a luxury):
<%= collection_select(:lang_id, 0, Language.all, :id, :name) %>
Where Language is a table with one column called 'name' and an auto-assigned column id; :lang_id is the name of the element and 0 is the default selected index when the page loads.
I have a website with a form for location on the front page. I want to auto-populate the form with values based on a URL string. How can I do this in rails?
For example, I would like the form to show with the value New York when the user arrives on the front page based on something like: website.com?city="New York"
How best to implement this in rails?
First of all, you can get the current request url, everything is here : How do I get the current absolute URL in Ruby on Rails?
Then you just have to "parse" it :
<% city = request.fullpath.split('=').last %>
Will return "New York" with a url like website.com?city="New York"
(Not sure about this one but maybe you can get it only with params[:city], I just don't think params is available in a view)
The rest depends on the structure of your form...
So I found some great info on Autocomplete for Rails 3, it looks really easy to use. But I have a use case that doesnt fit and I need some advice.
I want to give the user the ability to add Products and Services to an Invoice through a simple form. I'd like them to be able to type into the Item field and have it autocomplete from both Product.name and Service.name as a single set.
I'm thinking of trying to write a parent model that overlays all three, but I still don't think that solves my problem since I can't use a function in the autocomplete definition from what I understand.
Any advice on how I might try to accomplish this? Even with the simple search examples that are out there they seem to be restricted to a single model.
If you're not opposed to introducing Redis into the mix, have a look at https://github.com/seatgeek/soulmate -- From the README:
Soulmate is a tool to help solve the common problem of developing a fast autocomplete feature. It uses Redis's sorted sets to build an index of partially completed words and the corresponding top matching items, and provides a simple sinatra app to query them. Soulmate finishes your sentences.
Soulmate was designed to be simple and fast, and offers the following:
Provide suggestions for multiple types of items in a single query (at SeatGeek we're autocompleting for performers, events, and venues)
Results are ordered by a user-specified score
Arbitrary metadata for each item (at SeatGeek we're storing both a url and a subtitle)
An item is a simple JSON object that looks like:
{
"id": 3,
"term": "Citi Field",
"score": 81,
"data": {
"url": "/citi-field-tickets/",
"subtitle": "Flushing, NY"
}
}
Where id is a unique identifier (within the specific type), term is the phrase you wish to provide completions for, score is a user-specified ranking metric (redis will order things lexicographically for items with the same score), and data is an optional container for metadata you'd like to return when this item is matched (at SeatGeek we're including a url for the item as well as a subtitle for when we present it in an autocomplete dropdown).
See Soulmate in action at SeatGeek.
If nothing else, maybe it'll give you some ideas on how to structure the data in a way that makes sense.
I did not write or have anything to do with soulmate. It's just a library I discovered when trying to solve a similar problem. Hope it helps!
If client-side autocomplete is an option (e.g. you have few products and services), you could go with JQuery autocomplete:
controller:
#keys = #categories.map { |x| x.name } + #entries.map { |x| x.description }
#autocomplete_categories = #keys.to_json.html_safe
view:
<script type="text/javascript">
$(document).ready(function() {
var data = <%= #autocomplete_categories %>;
$("#auto").autocomplete( { source: data } );
});
</script>
<input type="text" name="auto" id="auto" />
I have this ruby on rails code
<%= builder.select(:serving_size_id, '') %>
I have not specified any options on purpose because I set the options in a different way when the page loads (using jQuery and Ajax).
The question: Is there any way I can get the value from the column "serving_size_id" but not change that line? I have a partial which I use it for new and edit and I think it would be sweet if I can do the setting of the selected index in JS.
Any ideas?
I'm not sure I completely understand your question, but if you want to set the value of the select field with JavaScript, you need to obtain the value in JavaScript at some point. I can think of two ways of doing this:
1) When you get the options via AJAX, have the server indicate which one is selected. This can be done by returning HTML <option> tags with selected="selected" set for one of them. To do this, your AJAX request is going to have to provide information about the object this select field is for (so the server can look up the object's current serving_size_id value).
2) When you render the field in your original partial, also render some JavaScript which sets the current value of the field, for example, underneath what you have above:
<%= javascript_tag "var ssid = '#{builder.object.serving_size_id}';" %>
Then, after the options are retrived via AJAX, the ssid variable is checked and the correct option is selected.
using jQuery in rails is easy but a little more difficult than prototype.
ex: "div id="serving_size" class="nice" rel="<%=h num%>">Stuff Goes Here.../div>"
in application.js do the following:
//application.js
$(document).ready(function(){
if($('#serving_size'){
$('#serving_size').live("mouseover",function(){
//we are hovering over specific div id serving size
if($('#serving_size').hasAttr('rel')){
alert($('#serving_size').attr('rel'); //your dynamic rel value, and fire function
}
}
}
if('.nice'){
$('.nice').live("mouseover",function(){
//we are now hovering over any item on page with class nice
if($(this).hasAttr('rel')){
//we are now using jQuery object ref and finding if that obj has attr rel
alert($(this).attr('rel')); // shows dynamic rel value
}
}
}
});
If you use the above code you should be able to do anything you want and fire any custom code from each of your set event callbacks.
The 'live' function in jQuery is great because it can be called on items that will eventually be on the page (eg. if you fill in something with ajax, jQuery will be prepared for that item being in the page)
I hope this help.