This is my form partial:
<%= f.simple_fields_for :photo_attributes, :html => { :multipart => true } do |d| %>
<%= d.label :image, :label => 'Upload logo', :required => false %>
<%= d.file_field :image, :label => 'Image, :required => false', :style => 'margin-bottom:2px' %>
<%= d.input :image_url, :label => 'Billed URL', :required => false %>
<% end %>
If the action is edit I want to show this instead:
<%= f.simple_fields_for :photo, :html => { :multipart => true } do |d| %>
<%= d.label :image, :label => 'Upload logo', :required => false %>
<%= d.file_field :image, :label => 'Image, :required => false', :style => 'margin-bottom:2px' %>
<%= d.input :image_url, :label => 'Billed URL', :required => false %>
<% end %>
How can i achieve this?
current_page?(action: 'edit')
See ActionView::Helpers::UrlHelper#current_page?
Rails also makes the methods controller_path, controller_name, action_name available for use in the view.
Generally the form partial only contains the fields, not the form tag or the fields for, but if you have no other way, you can always see what params[:action] is currently set to and behave accordingly.
You could write something like
<%- form_url = #object.new_record? ? :photo_attributes : :photo %>
<% f.simple_fields_for form_url, :html => { :multipart => true } do |d| %>
That is, if you have an #object to check against. Otherwise you could use action_name (and even controller_name).
So something like:
<%- form_url = action_name == :edit ? :photo : :photo_attributes %>
<% f.simple_fields_for form_url, :html => { :multipart => true } do |d| %>
Hope this helps.
Rails 5: Display Action within the view
<%= action_name %>
If statement within the view
<% if action_name == "edit" %>
This is an edit action.
<% end %>
Just use #_controller.action_name in view
Related
I have this nasty if/else statement in a rails view:
<% if question.field_type == "text_area" %>
<%= f.text_area :content, :class=>"form-control question-field", :data => {:question => question.id, :filter=> #filter}, :value=> question.answer(#assessment).try(:content) %>
<% elsif question.field_type == "date" %>
<%= f.date_select :content, { :order => [:year, :month, :day], :prompt => { :day => 'day', :month => 'month', :year=> "year" }, :end_year=> Date.today.year, :start_year => Date.today.year - 2 }, {:class => "question-field", :data => {:question => question.id, :filter=> #filter}, :value=> question.answer(#assessment).try(:content)} %>
<% elsif question.field_type == "text_field" %>
<%= f.text_field :content, :class=>"form-control question-field", :value=> question.answer(#assessment).try(:content), :data => {:question => question.id, :filter=> #filter} %>
<% elsif question.field_type == "dropdown" %>
<%= f.select :content, options_for_select(question.options), { :prompt => "Choose One..." }, :class=>"form-control question-field", :value=> question.answer(#assessment).try(:content), :data => {:question => question.id, :filter=> #filter} %>
<% elsif question.field_type == "number" %>
<%= f.select :content, options_for_select(1..10), {:include_blank=> true}, :class=>"form-control question-field", :value=> question.answer(#assessment).try(:content), :data => {:question => question.id, :filter=> #filter} %>
<% elsif question.field_type == "percentage" %>
<h2>100%</h2>
<%= f.range_field :content, :value=> get_percentage(question), :class=> "question-field percentage", :data => {:question => question.id, :filter=> #filter}, :step => 25, :in => 0..100 %>
<% end %>
Is there a good way to refactor this to make it nicer? This piece of code is in every field:
:class=>"form-control question-field", :value=> question.answer(#assessment).try(:content), :data => {:question => question.id, :filter=> #filter}
Do I refactor into a helper method or a partial?
Sometimes templates are just messy and you can only clean up detail. Refactoring into a parameterized partial will help. For goodness sake, use a case. And consider switching to HAML. It eliminates a lot of the visual clutter.
<%= render 'question_field', f: f, type: question.field_type %>
Then in _question_field.erb,
<%= case type %>
<% when 'text_area' %>
<% f.text_area :content, class: 'form-control question-field', %>
<% data: { question: question.id, filter: #filter }, %>
<% value: question.answer(#assessment).try(:content) %>
<% when ... %>
<% end %>
Note common industrial practice is to pick a max line length and stick to it: 100 and 120 are pretty common. Also, use the new symbol key notation for hashes. The old hook-and-arrow is too noisy.
In HAML:
= case type
- when 'text_area'
- f.text_area :content, class: 'form-control question-field',
data: { question: question.id, filter: #filter },
value: question.answer(#assessment).try(:content)
- when ...
I would get rid of if's and when's altogether by creating seperate partial for every possibility, then you just end up with:
<%= render question.field_type, locals: {question: question} %>
Or to make it even cleaner for view make helper method and call only
<%= question_field(question) %>
and this method would look little bit like
def question_field(question)
return render question.field_type, locals: {question: question}
# raise when no partial found, or do something elese
end
I have this simple_form
<%= simple_form_for(#order) do |f| %>
<%= f.error_notification %>
<%= f.association :orderstatus, :label => false, :include_blank => false, :input_html => { :class => 'order-status' } , :as => :radio, :label_html => { :style => "background-color:black;" } %>
<%= f.button :submit, :value => 'Update', :class => 'button grey small' %>
<% end %>
And it creates this: http://d.pr/9Bqd In the database I also have a field color which is a hex code for the background color I want of each status. Any idea how to pass this hex code onto each background label color?! I've tried for hours.
Have you tried passing it in like this...
# assuming "hex" is stored in the order model. Any variable should work
:label_html => { :style => "background-color:##{#order.hex};" }
If not, please respond with your results
Here is my view:
<%= form_tag({ :action => "display"}, :method => "get") do %>
<%= select(:music, :type, MusType::TYPES, {:include_blank => true}) %>
Here is my array constant in the model:
class MusType < ActiveRecord::Base
TYPES = ['Jazz','Rock','Blues']
end
My select menu draws values out of an array. How do I pass the selected value into the controller as a parameter after the submit button is pressed?
you can do something like below.
view code
<%= form_tag(:url => {:controller => "mycontroller" :action => "display"}, :method => "get") do %>
<%= select_tag(:music, :type, MusType::TYPES, {:include_blank => true}) %>
<%= submit_tag "Search", :id => 'search' %>
<% end %>
read the selected value in mycontroller.rb
def display
value = params[:music][:type]
// do something with value
end
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');"}%>
I'm trying to pass a string with a link_to_remote call as the :id, and the string should be collected from an input field with and id of "movie_title".
<div id="search_list">Nothing here yet</div>
<br />
<% semantic_form_for #movie do |f| %>
<% f.inputs do -%>
<%= f.input :title, :class => "movie_title" %> <%= link_to_remote( 'Search...', { :url => { :action => :imdb_search, :id => "'+$('\#movie_title').value+'" } }, { :title => "Search for this movie", :class => "imdb_search" } ) -%>
[...removed text that does not matter...]
<% end -%>
<%= f.buttons %>
<% end %>
I keep getting an javascript error, and if I remove the # from the jquery in the link, it returns "Undefined".
The link I get is:
<a class="imdb_search" href="#" onclick="jQuery.ajax({data:'authenticity_token=' + encodeURIComponent('yHPHYTZsPTQLi9JYSauUYcoie/pqPPk2uHBTN0PzNsQ='), dataType:'script', type:'post', url:'/movies/imdb_search/'+$('%23movie_title').value+''}); return false;" title="Search for this movie">Search...</a>
So I want the link updated with the contents of movie_title.
How do I do that?
I'd try something like
<%= link_to_remote( 'Search...', {
:url => { :action => :imdb_search},
:with => "'id=' + $('movie_title').value",
{:title => "Search for this movie", :class => "imdb_search"}
)
Fixed it
Used:
$('movie_title').val()
Insted of
$('movie_title').value