Rails help with select and render partial - ruby-on-rails

Want to create a select that tells what info to pass to the partial in a Rails 3 App.
Currently.
Lets say default is
<% orders_date_range = #orders.closed_today %>
Then
<div id="reports">
<%= render :partial => "report_details", :locals => { :orders => orders_date_range } %>
</div>
Can I create a select tag to pass in the orders_date_range? Or is there a better way of doing this?
UPDATE
<% orders = #orders.closed_today %>
<% #options = [["this week", #orders.closed_this_week],["this year", #orders.closed_this_year]]%>
<%= select 'orders', 'order', #options.collect {|f| [f[0], f[1]]}, :remote => true %>
<div id="reports">
<%= render :partial => "report_details", :locals => { :orders => orders } %>
</div>
Don't know why, but would only work with 'orders', 'order' for select.
applicaton.js
$("#orders_order").change(function(){
$.getScript("reports");
});
reports.js.erb
$("#reports").html("<%= escape_javascript(render :partial => 'report_details', :locals => { :orders => params[:selected] } ) %>");

Probably would be cool to do this as an AJAX thing....
Form.erb:
#call this at the top of your view
<%= javascript_include_tag :defaults %>
<%= select 'orders', 'option', #options.collect {|f| [f[0], f[1]]}, :onchange => remote_function(:url => {:action => :render_my_partial}, :with => 'Form.Element.Serialize(this)' %>
Controller:
def form
#options = [["option1", option1],["option2", option2]...]
end
def render_my_partial
render update do |page|
page.replace_html 'reports', :partial => 'report_details', :orders => params[:orders][:option]
end
end

Related

Passing a form as a local to a ajax rendered partial in Rails 5

I've looked all over and can't find a solution that works.
Relevant Controller (profits_controller.rb):
def new_tabs
#market = Market.order('mjsnumber').all.first
#profit = Profit.new
profit_types_markets_products
end
def fetch_market
#market = Market.where(:id => params[:market_id]).first
form = params["form"]
respond_to do |format|
format.js { render layout: false}
end
end
Relevant View (new_tabs.html.erb):
<%= simple_form_for #profit, :remote => true do |form| %>
<% #markets.each_with_index do |market, i| %>
<%= link_to market.nick, fetch_market_path(:market_id => market.id, :form => form, profit: #profit), :remote=>'true', :id => 'navBtn' + market.id.to_s, :class => 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<% end %>
<%= render :partial => 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } %>
Relevant Partial (_edit_partial_form.html.erb):
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
<%= figures_form.input "[test]" %>
<% end %>
Relevant JS (fetch_market.erb):
$("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Routes:
get "/fetch_market" => 'profits#fetch_market', as: 'fetch_market'
It renders the partial fine, and the links appear to contain the FormBuilder information. When I click the link and add a "puts params" to the controller, it shows the params there. But then gives me an error when loading the partial in console:
ActionView::Template::Error (undefined local variable or method `form' for #<#<Class:0x00007fdbd6453648>:0x00007fdbd68db5f8>
Did you mean? fork):
1: $("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Thanks in advance.
In fetch_market method you should to edit form = params["form"] to #form = params["form"]. You was declared local var this is why your code doesnt work. And the name of the file should be fetch_market.js.erb)

Rendering a partial N times instead of for each item in an array

I have a set of attributes that belong to a product, e.g. :name, :smalls, :mediums, :larges, :price, etc.
Right :smalls, :mediums, and :larges are arrays of strings:
#products = [
{ :id => 1,
:name => 'Product 1',
:description => 'description goes here',
:smalls => ['S'],
:mediums => ['M','M'],
:larges => ['L',],
:price => 50.0,
:names_and_numbers => 'optional'
}
]
The number of strings in each array determines the number of times the corresponding partial is rendered:
<div id="small-field-set">
<% product[:smalls].each do |small| %>
<%= render :partial => 'small', :locals => { :product => product, :small => small } %>
<% end %>
</div>
<div id="medium-field-set">
<% product[:mediums].each do |medium| %>
<%= render :partial => 'medium', :locals => { :product => product, :medium => medium } %>
<% end %>
</div>
<div id="large-field-set">
<% product[:larges].each do |large| %>
<%= render :partial => 'large', :locals => { :product => product, :large => large } %>
<% end %>
</div>
How can I have a number, rather than the size the array, determine how many times the partials is rendered?
I tried doing this:
{ ...
:smalls => [1],
:mediums => [2],
:larges => [1],
...
}
But that did not work.
When you do this...
{ ...
:smalls => [1],
...
}
...you still have an array: [1] is an array with one element, the integer 1 (just like [1, 2] is an array with two elements) . So first, you want to get rid of the arrays:
{ ...
:smalls => 1,
:mediums => 2,
:larges => 1,
...
}
For your view, when you use each you're saying, "do this one time for each item in the array." Since you now have a number, not an array, you can use times which, just like it sounds, means "do this N times":
<div id="small-field-set">
<% product[:smalls].times do %>
<%= render :partial => 'small', :locals => { :product => product, :small => "S" } %>
<% end %>
</div>
P.S. I'm not sure what the purpose of :small in the :locals hash is. Since your partial is called 'small' I'm guessing you don't need this, or can easily change your partial to get rid of it.
Why the array?
:smalls => 1,
Then
<% product[:smalls].times %>
<%= render :partial => 'small', :locals => {:product => product } %>
<% end %>

nil_class when using partial

I have the following code:
new.html.erb
<% form_for #car,:html => {:name => 'car_form'} do |f| %>
<% time_created = Time.new %>
<%= f.hidden_field :CAR_DATE_CREATED, :value => time_created %>
<%= render :partial => "car_partial", :locals => {:object => #car } %>
<%= f.submit 'Create' %>
<% end %>
_car_partial.html.erb
<% fields_for #car do |f| %>
Origin: <%= f.select(:ORIGIN_TYPE,
[['Origin X', 'X'],
['Origin Y', 'Y'],
['Other origin', 'Other']
],{:prompt => "Please select"}
) %>
<%= observe_field("car_ORIGIN_TYPE", :frequency => 2,
:url => { :controller => 'car',
:action => :display_other_origin },
:with => "'id='+value") %>
<span id="otherOrigin" > </span>
<% end %>
controller code
def display_other_origin
origin = params[:id]
end
display_other_origin.rjs
if params[:id] == "Other"
page['otherOrigin'].replace_html :partial => 'car/other_origin_type', :locals => {:car => #car }
else
page.replace_html :otherOrigin, ''
end
_other_origin_type.html.erb
<% fields_for #car do |f| %>
If other, please state: <%= f.text_field :ORIGIN_TYPE, :size => 20%>
<% end %>
If user selects 'Other origin', the partial is displayed correctly but when i do <view source>,
Origin: <select id="car_ORIGIN_TYPE" name="car[ORIGIN_TYPE]">
<option value="X">Origin X</option>
<option value="Y">Origin Y</option>x
<option value="Other">Other origin</option>
</select>
<script type="text/javascript">
//<![CDATA[
new Form.Element.Observer('car_ORIGIN_TYPE', 2, function(element, value) {new Ajax.Request('/cars/display_other_origin', {asynchronous:true, evalScripts:true, parameters:'id='+value + '&authenticity_token=' + encodeURIComponent('+MtiIQj/KfX2huaetD1E7W7f2pu/HC2d31BhCPjcmlQ=')})})
//]]>
</script>
<span id="otherOrigin">
If other, please state: <input id="nil_class_ORIGIN_TYPE" name="nil_class[ORIGIN_TYPE]" size="20" type="text">
</span>
nil_class is displayed instead of 'car'.
Any help???
Thanks
Your controller action display_other_origin is not setting the #car variable - so it is nil when used in the display_other_origin.rjs file.
Basically, in your observe_field method you need to also set a parameter for the car id. For example:
<%= observe_field("car_ORIGIN_TYPE", :frequency => 2,
:url => { :controller => 'car',
:action => :display_other_origin },
:with => "'id='+value+'&car_id='#{#car.id}") %>
Then you can do #car = Car.find(param[:car_id]) in display_other_origin
...although I should note that convention states that params[:id] - when passed to the CarsController - should be the car id, and your origin should be params[:origin]

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');"}%>

Rails collection_select

Manager :has_many :interns, :through => :assigns
Intern :has_many :managers, :through => :assigns
I am trying to create a new assign record. This is the assigns/new view where a given authenticated intern is creating a new association with a manager:
# assigns/new.html.erb
<% form_for #assign, :url => {:action => "create"} do |p| %>
<%= p.label "Select Manager", nil, :class => "label" %>
<%= collection_select :assign, :manager_id, #managers, :id, :manager_name, options ={:prompt => "Select a manager"}, html_options ={:class =>"listBox", :style => "width:25em;"} %>
<%= p.hidden_field :intern_id %>
<% end %>
# assigns controller
def new
#intern = Intern.find(params[:id])
#assign = Assign.new(:intern_id => #intern.id)
render :layout => 'centered'
end
def create
#assign = Assign.new(params[:assign])
#assign.manager_id = params[:manager_id]
if #assign.save
redirect_to :controller => "interns", :action => "home"
else
render :action => :new
end
end
The problem is: manager_id = nil. Why? Thanks very much.
Comment out following or
#assign.manager_id = params[:manager_id]
OR replace with
#assign.manager_id = params[:assign][:manager_id]
You don't need this line
#assign.manager_id = params[:manager_id]
You're already assigning the manager_id in the line before
#assign = Assign.new(params[:assign])

Resources