Trouble configuring search field to pass searched value into function - ruby-on-rails

I'm pretty new to Ruby on Rails, forms lately have been giving me all kinds of trouble so your help and support here would be very valuable.
In my home.html.erb file I have this code:
<%= form_tag({:controller => "pages", :action => "search"}, :method => "get", :class => "grabTweets") do %>
<%= text_field_tag(:tweets)%>
<% end %>
I'm trying to take the value that the user enters into that search field and pass it into a function called grabTweets that contains the following code:
def grabTweets(mySearch)
#tweet = Twitter.search(mySearch + "[pic] "+" instagr.am/i/", :rpp => 2, :result_type => "recent").map do |status|
#tweet = "#{status.text}" #class = string
urls = URI::extract(#tweet, "http") #returns an array of strings
end
end
The my form code in home.html.erb renders correctly but doesn't communicate with the grabTweets function. As much Googling and tinkering as I do, I can't seem to figure out the answer. The code in home.html.erb adds this to the end of my localhost URL: /assets?utf8=✓&tweets=google, so the search isn't being routed correctly.
Thanks in advance!

There are two things: first you need to make sure that your url gets routed to the write controller
match '/search', :to "pages#search"
ought to do it.
Then in your PagesController's search action, call
grabTweets(params[:tweets])
and do something interesting with the results. Obviously if grabTweets isn't an instance method on your controller then you'd need to adjust how you're calling it.

Your url is fine. For search, you should have the arguments passed in as GET params (as you currently are doing)
The problem is just how you're accessing the search argument. Instead of trying to read an argument in the function like this:
def grabTweets(mySearch)
#tweet = Twitter.search(mySearch + "[pic] "+" instagr.am/i/", :rpp => 2, :result_type => "recent").map do |status|
#tweet = "#{status.text}" #class = string
urls = URI::extract(#tweet, "http") #returns an array of strings
end
end
Read off the params hash:
def grabTweets
#tweet = Twitter.search(params[:tweets] + "[pic] "+" instagr.am/i/", :rpp => 2, :result_type => "recent").map do |status|
#tweet = "#{status.text}" #class = string
urls = URI::extract(#tweet, "http") #returns an array of strings
end
end
And this is Ruby. Please don't CamelCase variables.

Related

How to generate Excel file with passing params from AJAX search?

I'm performing AJAX search in my Rails application. Here is code from controller:
def show
#website = Website.find(params[:id])
if (current_user.id != #website.user_id)
redirect_to root_path
flash[:notice] = 'You are not owner!'
end
if params[:report] && params[:report][:start_date] && params[:report][:end_date]
#performance_reports = #website.performance_reports.where("created_at between ? and ?", params[:report][:start_date].to_date, params[:report][:end_date].to_date)
else
#performance_reports = #website.performance_reports
end
but when I'm trying to generate Excel document it alway goes to branch without params, because there are no params in URL.
One man reccomend me to use this post. I tried to implement it, but couldn't.
I don't understand this post enough, I just can't get where data is passing(spreadsheet gem)
Here is code:
def export
#website = Website.last
#data = #website.performance_reports
report = Spreadsheet::Workbook.new
spreadsheet = StringIO.new
contruct_body(spreadsheet, #data)
report.write spreadsheet
send_data spreadsheet.string, :filename => "yourfile.xls", :type => "application/vnd.ms-excel"
end
and it gives me error:
undefined method `contruct_body'
Code from view:
<%= form_tag( url_for, :method => :get, :id => "report") do%>
...show action posted above...
<% end %>
<%= link_to export_path do%>
<b>Export</b>
<% end %>
...working code without AJAX...
<%= link_to url_for(request.parameters.merge({:format => :xls})) do%>
<b>Export</b>
<% end %>
Please tell me where is my mistake or suggest ano
For the first problem, you need to show the view code and the path ajax is taking. Give us more information how the excel is being called.
For the second issue, you need to define that method. Specify how you will populate the spreadsheet with the data. Here is the guide. https://github.com/zdavatz/spreadsheet/blob/master/GUIDE.txt
== Writing is easy
As before, make sure you have Spreadsheet required and the client_encoding
set. Then make a new Workbook:
book = Spreadsheet::Workbook.new
Add a Worksheet and you're good to go:
sheet1 = book.create_worksheet
This will create a Worksheet with the Name "Worksheet1". If you prefer another
name, you may do either of the following:
sheet2 = book.create_worksheet :name => 'My Second Worksheet'
sheet1.name = 'My First Worksheet'
Now, add data to the Worksheet, using either Worksheet#[]=,
Worksheet#update_row, or work directly on Row using any of the Array-Methods
that modify an Array in place:
sheet1.row(0).concat %w{Name Country Acknowlegement}
sheet1[1,0] = 'Japan'
row = sheet1.row(1)
row.push 'Creator of Ruby'
row.unshift 'Yukihiro Matsumoto'
sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
'Author of original code for Spreadsheet::Excel' ]
sheet1.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'
sheet1.row(3).insert 1, 'Unknown'
sheet1.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'
Add some Formatting for flavour:
sheet1.row(0).height = 18
format = Spreadsheet::Format.new :color => :blue,
:weight => :bold,
:size => 18
sheet1.row(0).default_format = format
bold = Spreadsheet::Format.new :weight => :bold
4.times do |x| sheet1.row(x + 1).set_format(0, bold) end
And finally, write the Excel File:
book.write '/path/to/output/excel-file.xls'

How to I make a drop down beside a search box that searches the specific field selected in rails?

Okay so im new to this site but this is what I have:
Report.rb
def self.search(search)
if search
where('JOBLETTER_CD_NUMBER LIKE ? AND DATE LIKE? AND CUST LIKE ?', "%#{search}%")
else
scoped
end
end
end
index.html.erb
select_tag "search", options_for_select([ "Job Letter and CD #", "Date", "Cust", "Job", "Date shipped", "Date billed", "Billed by" ], params[:search])
form_tag reports_path, :method => 'get' do
text_field_tag :search, params[:search], :class=> "form-search", :align => "right"
<%= submit_tag "Search", :JOBLETTER_CD_NUMBER => nil, :class => "btn btn-success", :align => "right"
reports controller
def index
#report = Report.paginate(:per_page => 1, :page => params[:page])
#report = Report.search(params[:search]).paginate(:per_page => 1, :page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #views }
end
end
The only field it will search is the Job Letter and CD # field I need it to allow me to search whatever is selected in the drop down box. Btw I am using bootstrap fro js and css functions.
Your query has 3 placeholders ? but passed only one argument "#{search}" - if you run it like that, what you really should be getting is an exceptions stating
ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 3) ...
Also, your select_tag is outside the form, so it won't be passed to the controller at all. If you move it into the form, you'd have to rename (e.g. to column) it since the name search is already used by the text field. Then you could pass both the column and the search parameters to your search function to construct the query.
HOWEVER, this is not safe, since nothing prevents a user to pass in any other column by manipulating the post request, and since you can't use placeholders for column names, there's a danger of SQL injection as well.
There are many solutions out there to construct searches, no need to reinvent the wheel. Take a look at the ransack gem. Here's a recent Railscast on how to use it.

Rails accessing variable in email template

I'm still on the rather steep side of the Rails learning curve, so please pardon the rather simplistic nature of this question, but Google's just not proving very helpful.
So, my issue is this. I have a controller that is calling a mailer. (Code snippet below)
The problem I can't seem to get passed is that no matter how I try to access the values in the rhtml page, I either get errors or nothing at all.
This is the controller snippet (#person is working just fine. #item is what's not working)
if params[:id] == 'username'
item_value = #user[:login]
elsif params[:id] == 'password'
item_value = #user[:new_password]
end
#item = { 'name' => params[:id], 'val' => item_value }
ApplicantMailer.deliver_forgot(#person.email, #person, #item)
This is the mailer method snippet:
def forgot(recipient, person, item, sent_at = Time.now)
#subject = 'Site Password Retrieval'
#body['person'] = person
#body['item'] = item
#recipients = 'rdavis#localhost'
#from = CONTACT_EMAIL
#sent_on = sent_at
#headers = {}
logger.debug #body.to_yaml
end
This is the rhtml snippet:
Dear <%= #person.first_name %>,
You are receiving this email because you or someone else has used the lost <%= #item[:name] %> page from the login page.
Your <%= #item[:name] %> for your account is: <%= #item[:val] %>
So, like I said, when I try to access the values for the #item, if I use #item.name it throws a missing method error and if I use the version listed above, it doesn't show anything.
I know I'm working with a hash & thought that trying to access the keys like I showed here was the right way. Obviously, I'm missing something here.
Can someone point me in the right direction, please? Thanks!
You are using strings when creating your hash and symbols when accessing it.
You want the following:
#item = { :name => params[:id], :val => item_value }
Which is distinct from:
#item = { 'name' => params[:id], 'val' => item_value }
You can try this in irb with the following.
hash = {"a" => "val1", :a => "val2", "b" => "val3"}
hash["a"] => "val1"
hash[:a] => "val2"
hash["b"] => "val3"
hash[:b] => nil

Rails/ajax - whitespace and request.raw_post

I am starting to learn Ajax with rails.
I have a catalog index page with a text_field_tag querying db if it finds similar "section" results.
Index.html.erb
<h1>Catalogs</h1>
<label>Search by Section:</label>
<%=text_field_tag :section %>
<%= observe_field(:section,
:frequency=> 0.1,
:update=> "article_list",
:url=>{ :action => :get_article_list }) %>
<div id="article_list"></div>
Catalogs_controller.rb
def index
end
def get_article_list
#section = request.raw_post.split(/&/).first
#catalogList = "<ol>"
Catalog.find(:all, :conditions => ["section = ?", #section]).each do |catalog|
#catalogList += "<li>" + catalog.title + "</li>"
end
#catalogList += "</ol>"
render :text => #catalogList
end
Question:
request.raw_post renders something like:
xml&authenticity_token=tgtxV3knlPvrJqT9qazs4BIcKYeFy2hGDIrQxVUTvFM%3D
so I use
request.raw_post.split(/&/).first
to get the section query ("xml"). It works, however how can I do if the query have a whitespace. (like "Open Source") In fact, I have Open Source sections in my db, but request.raw_post.split(/&/).first renders Open%20Source. How can I manage this? Did I have to use a full text search engine to achieve it or there is another way?
Thanks a lot for your explanation!
Look over your logs, in them you will see the post and the params being passed. You should not need to do your own query-string splitting. You should be able to use params[:section] to get the post data.
As your comment implies, there's something missing. Your observe_field needs to tell the Rails helper what to do. Check out: http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/observe_field. Anyhow, you'll want to do something like:
observe_field(... # lots of parameters
:with => 'section'
)
And that should give you params[:section].

Rails: Preserving GET query string parameters in link_to

I have a typical search facility in my app which returns a list of results that can be paginated, sorted, viewed with a different records_per_page value, etc. Each of these options is controlled by parameters in the query string. A simplified example:
/search?q=test&page=2
Now say I need to display a set of links that set records_per_page value to 10, 20, 30. Each link must include the existing query parameters, which can be a very long set, plus a new per_page parameter.
/search?q=test&page=2& ... &per_page=10
/search?q=test&page=2& ... &per_page=20
/search?q=test&page=2& ... &per_page=30
Is there an easy way to do it with just link_to helper or I need to parse and reproduce the query string from previous request somehow?
link_to 'Link', request.query_parameters.merge({:per_page => 20})
link_to 'Link', params.merge({:per_page => 20})
The simplest way to merge the new params with the query parameters and NOT with all parameters (including those obtained through the path) is to merge with request.query_parameters
link_to 'Search', search_path(request.query_parameters.merge({ per_page: 20 }))
Otherwise you end up with query strings duplicating the path parameters, for example ?action=index&controller=products&foo=bar instead of ?foo=bar.
If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:
# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>
If you use it in multiple places, clean the params in the controller:
# your_controller.rb
#params = params.slice(:sort, :per_page)
# view
<%= link_to 'Link', #params.merge(per_page: 20) %>
You can just throw elements of the params hash at link_to. Like
link_to "some_other_link", "/search", :page => params[:page]
This works if the links you are processing aren't given to you by request.params.
require 'rack/utils'
require 'uri'
def modify_query url, options={}
uri = URI(url)
query_hash = Rack::Utils.parse_query(uri.query)
query_hash.merge!(options)
uri.query = Rack::Utils.build_query(query_hash)
uri.to_s
end
puts modify_query('/search?q=test&page=2&per_page=10', 'per_page' => 20)
puts modify_query('/search?q=test&page=2', 'per_page' => 30)
# Outputs
# /search?q=test&page=2&per_page=20
# /search?q=test&page=2&per_page=30
What about
<%= link_to 'Whatever', :overwrite_params => { :pear_page => 20 } %>
?
A bit late i know..
If your using this as a way to filter search results have a look at my helper :)
This automagicly removes all blank and unneeded params and add the class "selected" if all of it's new params were already set.
def search_to s, args={}
selected = 0
args.each do |k, v|
selected = selected + 1 if params[k] == v.to_s || ( params[k].nil? && v.blank? )
end
if #search_params_base.nil?
#search_params_base = request.parameters.clone
#search_params_base.delete(:action)
#search_params_base.delete(:controller)
#search_params_base.delete(:page)
#search_params_base.delete_if{|k, v| v.nil? || v.blank?}
#search_params_base.delete(:utf8) if #search_params_base[:keywords].nil?
end
search_params = #search_params_base.merge(args)
search_params.delete_if{|k, v| v.nil? || v.blank?}
link_to s, search_path + '?' + search_params.to_param, :class => selected == args.length ? 'selected' : nil
end
You can then just use this in your view:
search_to '$80 to $110', :price => 80..110
Or in your case:
search_to '30 per page', :page => params[:page], :per_page => 30

Resources