Rails 2 and ajax - few select lists - ruby-on-rails

I can't figure what i do wrong. I have few select lists:
Regions
Towns
Organizations
How it should works:
User selects region.
List of towns loads.
User selects town.
List of organizations loads.
User chooses organization.
I use ajax for that and i realized only auto-loading for list of towns and i can't do same thing for organization. Second select list DOESN'T POST at all!
Here is my code:
View
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region_id, :url => { :controller => :organizations, :action => :list_towns, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'region_id', :update => 'select_organization_idd', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region2_id, :url => { :controller => :organizations, :action => :list_region, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'o_id', :update => 'select_organization_idd2', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
Controller
def list_region
render :text => ActionController::Base.helpers.options_for_select((params[:preselect] ? [['Choose organization', -1]] : []) + Organization.map{|org| [ActionController::Base.helpers.truncate(org.name, :length => 155), org.id]})
end
def list_towns
region = Region.find(params[:region_id])
towns = Kladr.find(:all, :conditions => ['code LIKE ?', "#{region.code}%"])
render :text => ActionController::Base.helpers.options_for_select([['Choose town', -1]] + towns.map{ |t| ["#{t.socr}. #{t.name}", t.id] })
end
What do i do wrong? Also i use Rails 2, that why observe_field is not deprecated.

Do you use rails 3? The method observe_field is deprecated.
With rails 3 you must do something like this :
view
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort, {}, {:id => 'ajax1'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}, {}, {:id => 'ajax2'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
javascript.js.coffee
$('#ajax1').change = () ->
$.post(
url: '/organizations/list_towns'
data: {value: $('#ajax1').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
$('#ajax2').change = () ->
$.post(
url: '/organizations/list_regions'
data: {value: $('#ajax2').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
The implementation is probably wrong and could be refactored. I didn't test it. But you've got the idea.

Related

Load a hash on grouped_collection_select rails form

currently, I have a hash like this:
#lg = {
"Latin East Group" => [
{:id => 2, :name => "HONGKONG"},
{:id => 3, :name => "NINGBO, ZHEJIANG"},
{:id => 4, :name => "SINGAPORE"},
{:id => 5, :name => "LARCHMONT, NY"},
{:id => 6, :name => "CHICAGO, IL"},
{:id => 7, :name => "HAIPHONG"},
{:id => 8, :name => "DANANG"},
{:id => 9, :name => "HANOI"},
{:id => 10, :name => "MARSEILLE"},
{:id => 11, :name => "LONDON"},
{:id => 12, :name => "EDINBURGH"},
{:id => 13, :name => "AMSTERDAM"},
{:id => 14, :name => "HOCHIMINH"},
{:id => 15, :name => "SHANGHAI"}
],
"Latin West Group" => [],
"Others" => [
{:id => 16, :name => "Brazil" },
{:id => 17, :name => "Mexico" },
{:id => 18, :name => "Columbia"}
]
}
Now, I am using select2 with my form, and I wanna create a dropdown menu from that hash instance variable. I want the keys of the hash will be the optgroups, and the option values are gonna be the name sin the hash like Singapore, Brazil... Therefore, I am wondering what is the correct syntax for it. Currently, this is my code:
_form_body.haml:
%div.col-md-8
= f.grouped_collection_select :origin_locations, #lg, #lg.keys, #lg.values, {:selected => f.options[:origin_locations]}, {class: 'form-control select2-multiple origin_locations', :multiple => true}
pricing_histories_controller.rb:
def load_location_groups
#lg = {}
location_groups = LocationGroup.all.includes(:locations).each { |group|
#lg[group.name]= group.locations.map{|l| {id: l.id,name: l.name}}
}
# location_groups.each_with_index do |location_group, index|
arr = Location.where("id NOT IN (SELECT DISTINCT(location_id) FROM location_group_assignments)").pluck(:id,:name)
#location_groups = {}
#lg["Others"] = arr.map{ |e| {id: e.first, name: e.last}}
end
I will get the error:
ActionView::Template::Error (["Latin East Group", "Latin West Group",
"Others"] is not a symbol nor a string)
So, I am wondering what I am doing wrong here. Any suggestions would be appreciated. Thanks and have a nice day.

How to add custom name input field in rails simple_form_for

#tech_data = TagNode.first outputs below object from the controller .
p #tech_data
#<TagNode _id: 5119dcf74054448e576f3392, parent_id: nil, parent_ids: [], name: "categories", path: "categories", _type: "TagNode">
I have a form which has the fields name, _type, and category. But my object doesn't have the field category.
Here's my form
= simple_form_for #tech_data, as: :techtags, :url => view_techtags_technologies_path, :remote => true,:method => :get,:html => {:id => "upsert_techtags",:data => {:spinner => "#tech-ui"}} do |f|
%label.pull-left Type
= f.input :_type, :collection => tech_types, :label => false, :input_html => {:class =>"chzn-select", :data => {:placeholder => "Select Technology Type"}, :multiple => false}
%label.pull-left Name
= f.input :name, :type=>"text", :required => true, :label => false, :placeholder =>"Type the New Technology", :input_html => {:style => "width:265px;margin-bottom:0;"}
%label.pull-left Category
= f.input :category, :collection => [1,2,3,4], :label => false, :input_html => {:class =>"chzn-select", :disabled=>"true",:data => {:placeholder => "Type or select category"}, :multiple => false}
= f.submit "Create", :class => "btn btn-primary pull-right"
My form has an additional field that my object doesn't have. I get an error when the form is loaded, as I don't have category field in my object.
How can I select the category value in the form without adding this field to the model?
You need something like attr_accessor in Ruby,What is attr_accessor in Ruby?
Please include following in your model,which will make to get values from form to controller.
attr_accessor :category

Rails 3: Text_field_tag default value if params[:something].blank?

How would one do something like:
= f.input_field :age,
:collection => 18..60,
:id => 'age',
:selected => params[:age].blank? or "20"
Above doesen't work. I want to be able to set a default value if there is no param available for that attribute.
Any smart way to do this thx!
EDIT 1:
Full form:
= simple_form_for :people, :url => request.fullpath, :method => :get, :html => { :class => 'form-search' } do |f|
#container_search_small.form-search
= f.input_field :age,
:collection => 18..60,
:id => 'age',
:selected => params[:people][:age_from] || "20"
= f.submit "Go »"
You're using helpers that are taking their values from the object you're building the form on.
So in your controller, you should preset the values on the object.
def some_action
#people = People.new
#people.age = params[:age] || 20
end
Then in the form, remove the :selected option and it should be fine. Make sure you build the form for #people :
= simple_form_for #people, :url => request.fullpath, :method => :get, :html => { :class => 'form-search' } do |f|
#container_search_small.form-search
= f.input_field :age,
:collection => 18..60,
:id => 'age'
= f.submit "Go »"

How to save the radio button selection in database using rails

This is my controller:
class ReportNeedsController < ApplicationController
def index
#report_needs = nil
end
def new
#report_need = ReportNeed.new
end
def create
#report_need = ReportNeed.new(params[:report_need])
#report_need.save
redirect_to #report_need
end
end
This is my new.haml file:
Why do you want to report?
%form
%input{:name => "option", :type => "radio", :value => "spam"}
spam
%br/
enter code here
%input{:name => "option", :type => "radio", :value => "product_corrupted"}
product_corrupted
%br/
%input{:name => "option", :type => "radio", :value => "product_spoiled"}
product_spoiled
Make changes in view like :
%input{:type => "radio", :name => "report_need[product_type]", :id => "report_need[product_type]-1", :value => "salesforce", :checked => true}
%br/
%input{:type => "radio", :name => "report_need[product_type]", :id => "report_need[product_type]-2", :value => "salesforce", }
In controller, If product_type is field of table report_needs then no need to change in your action . else its change and store it like :
def create
report_need = ReportNeed.new(params[:report_need])
report_need.radio_field_name = params[:report_need][product_type]
report_need.save
redirect_to report_need
end

Rails pass ID from auto_complete field to observe_field

<p>Song Name:<%= text_field :songlists, :song_name, :id => "songlists_" + section.id.to_s + "_song_name" %></p>
<%= auto_complete_field "songlists_" + section.id.to_s + "_song_name", :method => :get,
:with => "'search=' + element.value", :url => formatted_songlists_path(:js) %>
<p>Artist:<%= text_field :songlists, :artist, :id => "songlists_" + section.id.to_s + "_artist" %></p>
<%= observe_field ("songlists_" + section.id.to_s + "_song_name", :update => "songlists_" + section.id.to_s + "_artist", :with => "element.value" , :url => { :controller => :songlists, :action => "get_artist" } ) %>
I have the auto-complete-field working fine, and the observe-field is triggering according to firebug, but I'm unsure how to update the text-field from the observe-field.
I either need to get the ID that the auto-complete finds, or even the text entered so that I can pass it into the :url of the observe-field.
Any ideas?
Can you walkthrough what you want this code to do?
I'm trying to get the response from the auto-complete field, to update another text-field with the results. I have the responses working now in firebug, but I can't seem to get it to update the box with the results.
<p>Song Name:<%= text_field :songlists, :song_name, :id =>
"songlists_" + section.id.to_s + "_song_name" %></p>
<%= auto_complete_field "songlists_" + section.id.to_s +
"_song_name", :method => :get,
:with => "'search=' + element.value",
:url => formatted_songlists_path(:js) %>
<p>Artist:<%= text_field :songlists, :artist %></p>
<%= observe_field "songlists_" +section.id.to_s + "_song_name",
:frequency => 0.5,
:url => { :controller => :songlists,
:action => :get_artist },
:update => "songlists_artist",
:with => "song_name" %>
controller code
def get_artist
#songlist = Songlist.find(:all, :conditions => ['name = ?', params[:song_name]])
if !#songlist.empty?
render :update do |page|
page.replace_html 'songlists_artist', :partial =>
'get_artist', :object => #songlist
end
end
end
In firebug I see this response
try {
Element.update("songlists_artist", "Robbie Williams");
} catch (e) { alert('RJS error:\n\n' + e.toString());
alert('Element.update(\"songlists_artist\", \"Robbie Williams\");');
throw e }
But it is not updating my text-field, any ideas?

Resources