Rails pass ID from auto_complete field to observe_field - ruby-on-rails

<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?

Related

syntax error, unexpected ')', expecting kEND

I received a syntax error message
<%= calendar_date_select_tag 'e_date', I18n.l( Date.today , :format=>:default),:year_range => 15.years.ago..5.years.from_now, :readonly=>true, :popup=>"force",
{:onchange => "#{remote_function(
:url => { :action => 'report_new' },
:with => "'start_date='+s_date+'end_date='+e_date+'&batch_id='+#{#batch.id}",
:before => "Element.show('loader')",
:success => "Element.hide('loader')" )}" }%>
try this ...
:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})
or
Dont mix your view/html with javascript(forget obstrusive javascript)
instead,there is one more cleaner way....
<%= select_tag :variable, options_from_collection_for_select(:all, :id, :name), :onchange => 'your_onchange_handler()' %>
<script type='text/javascript'>
$(document).ready(function(){
function your_onchange_handler(){
//do what u want to do when select changes
}
})//document ready ends
</script>

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 »"

Rails 2 and ajax - few select lists

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.

passing ruby variable in observe_field method

I would like to know how can I pass a ruby variable inside an observe_field method.
I have the following:
<% action_parameter = params[:action] %>
<%= observe_field :car_type,
:url => { :controller => 'cars',
:action => :display_subtypes },
:with => "'id=' + value + '&somevalue=' + action_parameter"
%>
'action_parameter' is a variable and I would like to pass its value in the observe_field method but the code above does not seem to work.
Any suggestion?
try this
<% action_parameter = params[:action] %>
<%= observe_field :car_type,
:url => { :controller => 'cars',
:action => :display_subtypes },
:with => "'id=' + value + '&somevalue=#{action_parameter}'"
%>
Ruby variable will work in <% .... %>
you can use interpolation , Try this :
<%= observe_field :car_type,
:url => { :controller => 'cars',
:action => :display_subtypes },
:with => "id=#{value}&somevalue=#{action_parameter}"
%>

Problem with ajax in date select

Excuse me, I am a newbie programmer in Rails.
I want use AJAX in a DATE SELECT. when I change the date, change the punitive ammount depends the result of method get_punitive (Model).
I use the next code in Controller, Model and View.However the event On change is not recognized. please you could help me.
Operations Model (partially)
def get_punitive(payment_date, expiration_date)
if payment_date > expiration_date
expiration_days= (payment_date - expiration_date).to_i
else
expiration_days = 0
end
punitive_ammount = (self.capital * (self.interest_rate_for_taker / 100.0) * expiration_days) / 30
# raise punitive_ammount.inspect
end
Operations Controller (partially)
def cancel
#operation = Operation.find(params[:id])
last_pagare = Pagare.find(:first, :conditions => "operation_id = #{#operation.id} AND state <> 'cancelled'")
#punitive_ammount = #operation.get_punitive(DateTime.now.to_date, last_pagare.expiration_date.to_date)
end
def update_payment_date
raise params.inspect
end
def submit_cancellation
#operation = Operation.find(params[:id])
ammount = params[:ammount]
punitive_ammount = (params[:punitive_ammount].blank?) ? 0 : params[:punitive_ammount]
payment_date = Date.new(params[:"payment_date(1i)"], params(:"payment_date(2i)"), params(:"payment_date(3i)"))
admin = User.find_by_login('admin')
if #operation.cancel(ammount, punitive_ammount, admin, payment_date)
respond_to do |format|
format.html { redirect_to(admin_operations_url) }
format.xml { head :ok }
end
else
#operation.errors.add_to_base("Los montos ingresados son invalidos")
render :action => 'cancel'
end
View of cancel
Cancelacion de Operaciones
<% form_for(#operation, :url => submit_cancellation_admin_operation_path) do |f| %>
<%= f.error_messages %>
<%= text_field_tag :a, :onClick => "javascript:alert('hola');" %>
<p>Fecha de Pago:<br/><br/>
<%= date_select("", :payment_date, {:start_date => Time.now, :onchange => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'payment_date='+value")}) %>
</p>
<p>Prueba
<%= collection_select "", :object, Operation.all, :id, :taker_id, { :onChange => "javascript::alert('hola');", :onClick => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'dgdfg='+value")} %>
</p>
<p>Monto a Cancelar (Mayor a cero):<br/><br/>
<%= text_field_tag :ammount , #operation.get_balance(#operation.interest_rate_for_taker) %>
</p>
<p>Monto punitorio:<br/><br/>
<%= text_field_tag :punitive_ammount, #punitive_ammount %>
</p>
<!--<p>Fecha de Pago:<br/><br/>
<%#= date_select("", :date, :start_year => Time.now.year-1, :default => Time.now) %>
</p>-->
<% %>
<p>
<%= f.submit 'Cancelar' %>
</p>
<% end %>
Hi format of date_select helper is
date_select(object_name, method, options = {}, html_options = {})
you have
<%= date_select("", :payment_date, {:start_date => Time.now, :onchange => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'payment_date='+value")}) %>
try
<%= date_select("", :payment_date, {:start_date => Time.now}, {:onchange =>"javascript::alert('hola');"}) %>
the same about collection_select
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
you have
<%= collection_select "", :object, Operation.all, :id, :taker_id, { :onChange => "javascript::alert('hola');", :onClick => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'dgdfg='+value")} %>
try
<%= collection_select "", :object, Operation.all, :id, :taker_id, {}, { :onChange => "javascript::alert('hola');"}%>

Resources