I'm using Rails3 to build a simple customer information page (in table format). On this page user can edit each customer's detailed information. It's possible for each customer to have multiple records. I use link_to to get to the edit page:
<td class="edit" id="edit">edit
<%= link_to 'edit', :action => :edit, :cust_id => ci.cust_id %>
</td>
edit.html.erb:
<h1>Editing cust</h1>
<%= form_for(#cust_info) do |cust| %>
Customer: <%= cust.text_field :cust_schema %>
<%= cust.submit "Save" %>
<% end%>
In my controller, I have this:
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
The customer info page shows right. When I click the edit link, I got the error message:
ActionView::Template::Error (undefined method `cust_info_cust_info_path' for #<#<Class:0x7fb0857ce7b8>:0x7fb0857ca780>):
1: <h1>Editing cust</h1>
2:
3: <%= form_for(#cust_info) do |cust| %>
4: Customer: <%= cust.text_field :cust_schema %>
5: <%= cust.submit "Save" %>
6: <% end%>
app/views/track/edit.html.erb:3:in `_app_views_track_edit_html_erb___102324197_70198065248580_0'
Where does `cust_info_cust_info_path' come from?
EDIT: here is the code in the controller:
class TrackController < ApplicationController
def display
end
def information
end
def customerinfo
#cust_info = CustInfo.find(:all, :order=>"cust_id")
#cust_info.each do |ci|
if ci.upload_freq == 'W'
ci.upload_freq = 'Weekly'
elsif ci.upload_freq == 'M'
ci.upload_freq = 'Monthly'
end
end
end
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
end
end
Change #cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
to
#cust_info = CustInfo.find(cust_id)
Related
When I write city in field and click button, on page has to be that name of city and another. In my case every time name is New York. When I write for example Las Vegas my link is http://localhost:3000/?query=Las+Vegas&commit=Search, the data on the page is about New York.
class HomeController < ApplicationController
def index
require 'net/http'
require 'json'
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
#uri = URI("http://api.weatherstack.com/current?access_key=1dbc1a3aa6b2e76a0c8eda1cba0c9c8b&query=#{#params[:query]}")
#uri.query = URI.encode_www_form(#params)
#json = Net::HTTP.get(#uri)
#api_response = JSON.parse(#json)
if #params[:query].empty?
#city = "Enter city"
#temperature = "(in English)"
else
#city = " #{#api_response['location']['name']}"
#temperature = "#{#api_response['current']['temperature']}°"
end
end
end
routes.rb
Rails.application.routes.draw do
root 'home#index', :as => 'search'
end
index.html.erb
<div class="main">
<h1 class="weather">Weather</h1>
<%= form_with(url: search_path, method: "get", local: true) do %>
<%= text_field_tag(:query) %>
<%= submit_tag("Search",class: "btn btn-primary") %>
<% end %>
<div class="city"> <h1><%= #city %> <h5><%= #temperature %></h5></h1> </div>
</div>
It looks like you have hardcoded New York in your params.
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
So you need to change this to be something like:
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => params[:query]
}
I try to pass 2 options for search. First [:q] for input text by visitor and another one from model camping "nomdep" (like departement in english). When i try to search by input it's works, but since i try to add select_tag i have an error
ERROR
undefined method `map' for nil:NilClass
I m lost, do u have any ideas ?
Sorry for my english, i m french.
Home_controler.rb
def index
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q,:nomdep]
#camping = Camping.all
end
end
def result
if params[:q].nil?
#campings = []
else
#campings = Camping.__elasticsearch__.search(params[:q]).page(params[:page]).per(14).results
end
end
View
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= select_tag(:nomdep, options_for_select(#camping)) %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
</div>
EDIT
Now i dont have any error but the search dont work if [:q] empty. So if i only select_tag => no result.
How fix this ?
My full home_controller.rb
class HomeController < ApplicationController
def index
#camping = Camping.all
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q, :nomdep]
end
end
def result
if params[:q].nil?
#campings = []
else
#campings = Camping.__elasticsearch__.search(params[:q]).page(params[:page]).per(14).results
end
end
end
my view
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= select_tag :nomdep, options_from_collection_for_select(#camping, :id, :nomdep), prompt: "Département" %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
</div>
#camping = Camping.all
This variable will be nil unless :q was passed in params to index action. options_for_select(#camping) will attempt to call #map on this variable and raise error when it is not initialized.
You should make sure it is initialized. For example, try rewriting your action:
def index
#camping = Camping.all
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q]
end
end
I want to say a big big big THANKS to #Baradzed ! We talked yesterday and he find a solution thats work perfectly !
home_controller.rb
class HomeController < ApplicationController
def index
#camping = Departement.all
if params[:q].blank? || params[:nomdep].blank?
#campings = Camping.__elasticsearch__.search params[:nomdep]
else
#campings = Camping.__elasticsearch__.search params[:q]
end
end
def result
querystring = params.slice(:nomdep, :other_param, :any_params_except_q_because_we_will_process_q_separately)
.select{|k,v| v.present?}
.map {|key, value| "#{key}:\"#{value.gsub(/([#{Regexp.escape('\\+-&|!(){}[]^~*?:/')}])/, '\\\\\1') }\""}
.join(" AND ")
freetext = params[:q]
freetext.gsub!(/([#{Regexp.escape('\\+-&|!(){}[]^~*?:/')}])/, '\\\\\1')
querystring = ["*#{freetext}*",querystring].select{|v| v.present?}.join(" AND ") if params[:q].present?
if querystring.blank?
flash[:notice] = "Aucune mots clefs"
redirect_to action: :index and return
else
#campings = Camping.__elasticsearch__.search(
query: { query_string: {
query: querystring
}}).page(params[:page]).per(14).results
end
#hash = Gmaps4rails.build_markers(#campings) do |camping, marker|
marker.lat camping.latitude
marker.lng camping.longitude
marker.infowindow render_to_string(:partial => "/campings/infowindow", :locals => { :camping => camping})
marker.picture ({
"url" => "http://avantjetaisriche.com/map-pin.png",
"width" => 29,
"height" => 32})
end
end
end
view
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= select_tag :nomdep, options_from_collection_for_select(#camping, :nomdep, :nomdep), prompt: "Département" %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
i need update a single record attribute but i can´t. alumno_id is foreign key of model 'alumno'. the code show the records and if submit 'Aceptar' in one record, need a change the attribute estado to 1
in Model
class Postulacion < ActiveRecord::Base
attr_accessible :ramo, :estado, :alumno_id
belongs_to :alumno
end
in View
<h1>Lista de Postulaciones</h1>
<% #postulaciones.each do |p| %>
<% #id = p.id %>
<%= #id %>
<p>
<td><%= Alumno.find(p.alumno_id).full_name%></td>
<td><%='=> '+ p.ramo %></td>
<td><% if p.estado == 0 %>
<%= 'Pendiente =>' %>
<%= form_tag :action => 'aceptar' do %>
<%= submit_tag 'Aceptar' %></p>
<%end%>
<%else%>
<%='=> Aceptado' %>
<%end%>
</td>
</p>
<% end %>
in controller
class ListadoController < ApplicationController
def listar
#postulaciones = Postulacion.all
respond_to do |format|
format.html
format.json { render json: #postulaciones }
end
end
def aceptar
#postulacion = Postulacion.where(id: #id).first #Edit
#postulacion.estado = 1 #Edit
#postulacion.save #Edit
redirect_to "/"
end
end
Error "undefined method `update_attribute' for []:ActiveRecord::Relation"
Thanks
With this code:
#postulacion = Postulacion.where(alumno_id: #id )
You are declaring #postulacion as a collection, not as a single instance. You can fix this by calling .first:
#postulacion = Postulacion.where(alumno_id: #id ).first
Or by using find_by instead of where:
#postulacion = Postulacion.find_by(alumno_id: #id )
One other thing - this code isn't checking for the possibility that the Postulacion instance might not exist. You should add some logic to handle this...
Your #postulacion variable holds ActiveRecord::Relation instead of single ActiveRecord object. Try:
def acceptar
#postulacion = Postulacion.find_by_alumino_id(#id)
# ...
end
or, if you'd be using Rails 4:
#postulacion = Postulacion.find_by(alumino_id: #id)
Hello everybody who likes RAILS, i have a problem i'm trying to export by "ejecutive_id" to XLS but i'm not doing the correct code,
-I created a select box where i can select all my ejecutives.
-I created another select box where i can select by status_id.
-I selected 1 ejecutive for example "Mogan" (ejecutive_id = 1)
-I selected 1 status form example "active" (status_id = 0 )
-After selecting both select boxes i click on "SEARCH"
-After doing SEARCH i'm getting my results (#list_policies this value in my code is before respond format)
Here is my controller
****PROJECT/APP/CONTROLLER/policy_managment/policy.rb********
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#search_ejecutive = params[:search_ejecutive]
#search_status = params[:status_id]
#list_ejecutives_comision = Ejecutive.find(:all)
#list_policies_search = Policy.deleted_is(0)
if params[:search_ejecutive].to_i!=0
#list_policies_search = #list_policies_search.ejecutive_id_is(#search_ejecutive)
end
if !params[:status_id].blank?
if params[:status_id].to_i != 3
#list_policies_search = #list_policies_search.state_is(params[:status_id])
end
else
#list_policies_search = #list_policies_search.state_is(0)
end
#status_id = params[:status_id]
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies_search = #list_policies_search.deleted_is(0)
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
#results = #list_policies_search.find(:all,:conditions=> { :ejecutive_id => #search_ejecutive })
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end
Here maybe could be the problem,also those are my links where i can export
*********HERE IS MY VIEW***********
<% form_remote_tag :url=>{:action=>"generate_print_ejecutive_comercial"},:before=>"load_close('loading_search')",:success=>"load_off('loading_search')" do -%>
<label>EJECUTIVES:</label>
<%= select_tag 'search_ejecutive',"<option value=\"\">Select</option>"+options_for_select(#list_ejecutives_comision.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>
</span>
<label>STATUS :</label>
<%= select_tag "status_id","<option value=\"3\">ALL</option>"+options_for_select([["active",0],["cancel",1],["no cancel ",2]],0) %>
</span>
<input name="Buscar" value="SEARCH" type="submit" /><span id="loading_search"></span>
<% end %>
#HERE WITH THOSE LINKS I'M EXPORTING ONLY MY FIRST 10 VALUES
<%= link_to("Export Excel","http://localhost:3000/policy_management/policy/generate_print_ejecutive/generate_print_ejecutive_comercial.xls")%>
<%= link_to "Export XLS",:controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial",:format=>"xls" %>
<%= link_to 'PRINT PDF', :controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial", :format=>"pdf" %>
I'm exporting my partial view and it depends of this
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
Here is my partial view and i'm using #list_policies
********************PARTIAL VIEW THAT I WANT TO EXPORT*********
<table>
<% #list_policies.each do |policy| %>
<tr>
<td><div class="nobreak"><%= policy.num_policy%></div></td>
<td><div class="nobreak">
<% if !policy.ejecutive.blank? %>
<%= policy.ejecutive.name %><%= policy.ejecutive.lastname1 %><%= policy.ejecutive.lastname2 %>
<% end %></div>
</td>
<td><div class="nobreak"><%= policy.str_state%></div></td>
</tr>
</table>
Seems that i need to add some params to my links_to....format.... i don't know what to add
Somebody can check this code?
It seems like using an options hash to dynamically build your query might be easier / cleaner. I would do it like this:
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#list_ejecutives_comision = Ejecutive.find(:all)
policy_options = {:deleted => false}
policy_options = policy_options.merge({:ejecutive_id => params[:search_ejecutive]}) unless params[:search_ejecutive].blank?
policy_options = policy_options.merge({:state => params[:status_id]}) unless params[:status_id].blank? and (params[:status_id] != 3)
#list_policies_search = Policy.all(policy_options)
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end
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.