newbe question here.
I've inherited a rails project and been asked to change some chunk of code, but I have a very little experience in Ruby and Rails (I am an objective-c with a PHP background developper)
So the first stuff I have to had is a textfield with an auto complete mode. Actually my code has this code for the auto completed text field :
registration_controller.rb
def auto_complete_for_training_title
puts "auto_complete_for_training_title"
current_locale = params[:locale].to_s
if current_locale == 'en' then
if current_user.member then
Locale.set current_user.member.written_language
else
Locale.set 'fr'
end
end
#trainings = Training.find(:all, :conditions => ["((title LIKE ? OR fso_id LIKE ?) and is_private = 0", '%' + params[:training][:title] + '%', '%' + params[:training][:title] + '%'])
puts #trainings.count
render :partial => 'complete_ajax_own_function_training'
end
In the view, the text field is created like this :
<% form_for :sortRegistration, { :url => { :action => 'index'} } do |f| %>
<p><label><%= "Display registrations by training".t %> :</label>
<%= text_field_with_auto_complete :training, :title, { :size => 50, :tabindex => 1 },
{ :select => 'mon_titre',
:after_update_element => "function(element,val)
{
var nodes = val.select(['.value_title']) || [];
if(nodes.length>0)
{
$('sortRegistration_training_id').value = Element.collectTextNodes(nodes[0], 'value_title');
}
}"
}
%></p>
<input id="sortRegistration_training_id" name="sortRegistration[training_id]" type="hidden" size="20" value="" />
<% end %>
If I copy / paste the code, only one textField works, I've tried to change some parameters but still not changing something.
P.S. As I said I am new in the RoR, I do not know if you need more code for help me so please, feel free to ask more, I will edit my question
Related
I was trying to implement a Search Bar and when i tested, it worked in a strange way: only the last letters could be found, or the whole name.
I'm sorry if the problem is simple to solve, i'm new to Ruby On Rails, and i really need this fixed and i couldn't find out how to fix it myself.
(Sorry about my bad English)
Here's my html:
<div class="search">
<%= form_for root_path, :url => {:action => "search"}, class: 'navbar-form' do |f| %>
<%= text_field_tag 'ad[price_min]', #ads_min, :placeholder => "Price min", class: "form-control embed-responsive-item" %>
<%= text_field_tag 'ad[price_max]', #ads_max, :placeholder => "Price max", class: "form-control embed-responsive-item" %>
<%= text_field_tag 'ad[title]', #ads_text, :placeholder => "Search xablau by name", class: "form-control embed-responsive-item" %>
<button class="btn btn-info" ><i class="glyphicon glyphicon-search"></i></button>
<% end %>
</div>
Here's my controller:
def search
if params[:ad].present?
#ads_min = params[:ad][:price_min]
#ads_max = params[:ad][:price_max]
#ads_title = params[:ad][:title]
#ads = Ad.search( params[:ad] )
else
#ads = Ad.all
end
render :action => 'index'
end
Here's my model:
def self.search(query)
price_min = query[:price_min].present? ? "price >= #{query[:price_min].to_f}" : nil
price_max = query[:price_max].present? ? "price <= #{query[:price_max].to_f}" : nil
title = query[:title].present? ? "title LIKE '%#{query[:title]}'" : nil
query = [title, price_min, price_max].compact.join(" AND ")
return Ad.where( query )
end
You have to use ILIKE and %text% instead of %text
title = query[:title].present? ? "title ILIKE '%#{query[:title]}%'" : nil
Because %text% matches with any string that contains text but %text matches only with string that have text on the end of string.
PS: you have to rewrite the search method because it's insecure put a user based text in sql. Do not do that "title LIKE '%#{query[:title]}'" Write something like that where("title ILIKE ?", "%#{params[:q]}%")
How can I use simple_form to filter a field, based on a previous fields value?
For instance, I have an Opportunities form, with two fields, Company and Contact.
Company Field:
<div class="form-group">
<%= f.association :company, collection: Company.all.order(:account), prompt: "", :label_method => :account, :value_method => :id %>
</div>
Contact Field:
<div class="form-group">
<%= f.association :contact, collection: Contact.all.order(:first_name), prompt: "", :label_method => lambda { |contact| "#{contact.first_name} #{contact.last_name}" }, :value_method => :id %>
</div>
Here is what I want to do: If I select a company called "Deviant" from the Company field above, I want the Contact field to only display those contacts associated with the company called "Deviant".
I am trying something like this, but can't get it to work:
<div class="form-group">
<%= f.association :contact, collection: Contact.where("company_id = ?", params[:id]), prompt: "", :label_method => lambda { |contact| "#{contact.first_name} #{contact.last_name}" }, :value_method => :id %>
</div>
I don't know how to reference the value in the Company field.
How can I do this?
Thanks.
Update
Anyone? Surely this must be possible. This is a key functionality in any form. I would hope I don't need jQuery or something.
I think the best approach is to use ajax requests to update your contacts collection dinamically whenever the company's selected value is changed.
First you'll need an action in your contacts controller:
app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
def contacts_list
if params[:company_id]
#contacts = Contact.where(company_id: params[:company_id])
else
#contacts = Contact.all
end
respond_with(#contacts) do |format|
format.json { render :json => #contacts.to_json(:only => [:id, :first_name, :last_name]) }
end
end
end
Add this to your routes:
config/routes.rb
post 'contacts_list' => "contacts#contacts_list", as: :contacts_list
Then use the coffeescript code bellow to populate your contacts' collection:
app/assets/javasctipts/companies.js.coffee
$(document).ready ->
if $("#opportunity_company_id")
populate_contacts()
$("#opportunity_company_id").change ->
populate_contacts()
populate_contacts = ->
$contacts_select = $("select#opportunity_contact_id")
$contacts_select.attr "disabled", "disabled"
company_id = $("select#opportunity_company_id").val()
if company_id is ""
$contacts_select.html "<option value=\"\">(select the company first)</option>"
else
$contacts_select.html "<option value=\"\">(loading contacts...)</option>"
data = {company_id: company_id}
data[window._auth_token_name] = window._auth_token
$.ajax "/contacts_list",
type: "post"
dataType: "json"
data: data
success: (contacts) ->
_html = '<option value="">Select the contact:</option>'
_html += '<option value="'+contact.id+'">'+contact.first_name + ' ' + contact.last_name + '</option>' for contact in contacts
$contacts_select.html _html
$contacts_select.removeAttr "disabled"
error: ->
alert 'Error trying to load contacts.'
Finally, inside your html's head tag:
<% if protect_against_forgery? %>
<script>
window._auth_token_name = "<%= request_forgery_protection_token %>";
window._auth_token = "<%= form_authenticity_token %>";
</script>
<% end %>
Hope it helps...
update:
Add the following line to your ApplicationController (app/controllers/application_controller.rb):
respond_to :html, :xml, :json, :js
I'm trying to make report page, on which user will choose start and end date and push buttopn report. Then hidden div became visible.
My search isn't on partial.
I am using jquery_datepicker so here is my code from view:
<%= form_tag(:controller => "financial_reports", :action => "index", :method => "post")%>
<%= datepicker_input "financial_report","start_date", :dateFormat => "dd/mm/yy" %>
<%= datepicker_input "financial_report","end_date", :dateFormat => "dd/mm/yy" %>
<%= submit_tag "Run Report"%>
<% end %>
Here is my code from controller:
def search
#financial_reports = current_user.financial_reports.search(params[:start_date], params[:end_date]
render :index
end
In my Model:
def self.search(from,to)
find(:all, :conditions => [ "BETWEEN ? AND ?", from, to])
end
And it gives me error:
ActiveRecord::StatementInvalid in FinancialReportsController#search
SELECT `financial_reports`.* FROM `financial_reports` WHERE `financial_reports`.`user_id` = 67 AND (BETWEEN NULL AND NULL)
and below this:
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"AMobLLRV3aAlNn6b4Au+1nRP2AN1TLQcBCytBXhDA/g=",
"type"=>"",
"financial_report"=>{"start_date"=>"05/08/2012",
"end_date"=>"11/08/2012"},
"commit"=>"Run Report",
"method"=>"post"}
Where is my error ?
If both parameters are set at all times, you can use:
#financial_reports = current_user.financial_reports.where(:created_at => ((params[:start_date].to_date)..(params[:end_date].to_date))
If that's not the case, you could (for example) do this:
#financial_reports = current_user.financial_reports
if params[:start_date].present?
#financial_reports = current_user.financial_reports.where("created_at >= ?", params[:start_date])
end
if params[:end_date].present?
#financial_reports = current_user.financial_reports.where("created_at <= ?", params[:end_date])
end
You will probably want to encapsulate this in scopes.
I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");
I want to create a very simple search partial. It has a text box, to query, and search db. Can I create a remote_function call without using AJAX or JS? Can I keep it entirely "Rails-ee"?
<%= text_field_tag "search_term",'', :size => 10 %>
<%= button "search", :onclick => remote_function( :url => {:action => :fill_in_lots },
:with => "search_term" ) %>
This isn't a problem, you need to use a technique called formal link. Instead of button you put a from with submit button. Below is a code of helper I use for this:
def formal_link_to(*args, &block)
options = html_options = name = nil
if block_given?
options = args.first
html_options = args.second
name = capture(&block)
else
name = args.first
options = args.second || {}
html_options = args.third
end
method = html_options.delete(:method) || "POST"
method = method.to_s.upcase
url = url_for(options)
html = "<form class=\"formal-link\" action=\"#{url}\" method=\"post\">"
html += "<input type=\"hidden\" value=\"#{form_authenticity_token}\" name=\"authenticity_token\" />"
html += "<input type=\"hidden\" value=\"#{method}\" name=\"_method\" />"
html += link_to(name, "#", html_options)
html += "</form>"
if block_given?
concat(html)
else
return html
end
end
You use this helper like a normal link_to, but you can pass extra options :method in second hash. Example:
<%= formal_link_to "Fill in lots", { :action => "fill_in_lots" }, { :method => :post } -%>
Remarks:
1. This of course will make the full page reload, but it is inevitable without using JavaScript.
2. I assumed action fill_in_lots is exposed to POST request. In case of GET you can use normal link_to helper.