Got a (hopefully) easy one:
Ruby partial view with a collection_select, need the value of that selection (var name = 'submod') passed as a param up to controller. Literally just stuck on how to get from collection_select/onchange() to named param.
html.erb code:
<% #modName = locals[:moduleName] %>
<% #id = locals[:id] %>
<%= form_with url: admin_command_path() do |f| %>
<%= collection_select(#refcode, :Code, Command.where(FLD: #modName), :Code, :Definition, options ={prompt: true}, html_options = {:onchange => "updateSubMod(this.value)"}) %>
<br /><br />
<button class="btn_new">
<%= link_to "Execute", new_admin_command_path(mod: #modName, submod: #refcode, id: #id) %>
</button>
<% end %>
The onchange function works as expected, so feel free to make use of that to solve for param:
<script>
function updateSubMod(Code) {
var submod = Code
console.log(submod, '********************')
}
</script>
I am using filterrific gem to add filters in my app. I have parents table and children table. On the children_list page which displays list of all the children with their firstname and their parent's firstname. The issue I am facing is in the search query I want to add the parent.firstname search as well for filterrific. I tried adding a join as below:-
num_or_conds = 2
joins(child: :parent).where(
terms.map { |term|
"(LOWER(children.firstname) LIKE ?) OR (LOWER(parents.firstname) LIKE ?) "
But this didnt do the job. Any idea how this can be achieved.
parent.rb
has_many :children
child.rb
belongs_to :parent
filterrific(
available_filters: [
:search_query,
:with_clinic_date
]
)
scope :search_query, lambda { |query|
return nil if query.blank?
terms = query.downcase.split(/\s+/)
terms = terms.map { |e|
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
num_or_conds = 2
where(
terms.map { |term|
"(LOWER(children.firstname) LIKE ?) OR (LOWER(parents.firstname) LIKE ?)"
}.join(' AND '),
*terms.map { |e| [e] * num_or_conds }.flatten
)
}
scope :with_clinic_date, lambda { |ref_date|
where('children.clinic_date = ?', ref_date)
}
end
_children.html.erb
<h1>Children</h1>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Parent First Name</th>
<th>Child firstname</th>
</tr>
</thead>
<tbody>
<% #children.each do |child| %>
<tr>
<td><%=child.parent.firstname %></td>
<td><%=child.firstname %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
</div>
children-list.html.erb
<%= form_for_filterrific #filterrific do |f| %>
<div class="row">
<div class="col-sm-3">
Search
<%= f.text_field(
:search_query,
class: 'filterrific-periodically-observed form-control'
) %>
</div>
<div class="col-sm-3">
Request Date
<%= f.date_field(:with_clinic_date, class: 'js-datepicker form-control') %>
</div>
<div class="col-sm-3">
<br>
<%= link_to(
'Reset filters',
reset_filterrific_url,
) %>
</div>
</div>
<%= render_filterrific_spinner %>
<% end %>
<%= render( partial: 'children/children_list') %>
children.js.erb
<% js = escape_javascript(
render(partial: 'children/children_list')
) %>
$("#filterrific_results").html("<%= js %>");
AFAIK, you can't filter two separate classes on the same page. It will use the last defined filterrific instance. When I ran into this problem, I used remote forms with custom action/routes
# routes.rb
resources :parent do
get :filter_parents
resources: children do
get :filter_children
end
end
And then the controllers..
# parents_controller.rb
def index
parents_filter # this would be a helper method running your filter queries
end
def filter_parents
parents_filter # this would be a helper method running your filter queries
end
The children's controller would look similar, just different named helper method/custom action.
And then use a partial for the table. Target the table's container, and use a filter_parents.js.erb and filter_childrens.js.erb file
$('#parents-table').html('<%= escape_javascript render 'path/to/partial'%>')
// same in childrens.js.erb, just target the appropriate table
I am trying to use for loop to show more images on one page.
I have tried
<% #products.each do |product| %>
<div class="col-xs-3">
<div class="thumbnail">
<img src="https://images.pexels.com/photos/96974/pexels-photo-96974.jpeg?h=350&auto=compress&cs=tinysrgb" alt="...">
<div class="caption">
<h3><%= product[:name] %></h3>
<p><%= product[:description] %></p>
<p>Button Button</p>
</div>
</div>
</div>
<% end %>
It is my home controller which I add below:
class HomeController < ApplicationController
def index
#ad = {
title: "大型广告",
des: "这是广告",
action_title: "这是广告",
}
#products = {
id: "1",
name: "柳橙汁",
description: "好喝的柳橙汁",
image_url: "https://images.pexels.com/photos/96974/pexels-photo-96974.jpeg?h=350&auto=compress&cs=tinysrgb",
}
end
end
It shows no implicit conversion of Symbol into Integer.
If #products is a query Ex. #products = Product.all
You can use product.name instead of [:name]
This answer is based on your (now deleted) comment:
After I tried your solution†, it says undefined method `name' for [:id, "1"]:Array
† using product.name instead of product[:name]
Your #products array contains other 2-element arrays like this:
#products = [[:id, "1"], [:id, "2"], [:id, "3"]]
Therefore each product refers to one of these inner arrays and product[:name] results in the error message:
product = #products.first
#=> [:id, "1"]
product[:name]
# TypeError (no implicit conversion of Symbol into Integer)
You solve this problem by changing what's inside the #products array. It should be instances of Product, not other arrays. The assignment probably occurs in your controller.
Question is I have a query that looks at my emp_id text box once something is typed in it searches for the information tied to that emp_id which in my other table that it searches for its called ID.. If the emp_id matches the id in my visual model it will populate their first name for them. I would like to know how I can get it to display an error if no emp_id matches an id in my visual model....
This is what I have so far but I keep getting a no method error....
This is the error
NoMethodError (undefined method `emp_matches' for #<Visual:0x00000005a4c8d8>):
app/controllers/user_controller.rb:31:in `populate_form'
This is my user controller.
class UserController < ApplicationController
def populate_form
#visual = Visual.find_by_id(params[:emp_id])
#emp_first_name = #visual.first_name
if #visual.emp_matches(#emp_id).id
flash[:notice] = "Emp Id found"
render :json => {
:emp_first_name => #emp_first_name
}
else
flash[:error] = "Emp ID not found"
end
end
This is my visual model..
class Visual < ActiveRecord::Base
establish_connection :vtest
self.table_name = 'employee'
Visual.inheritance_column = 'inheritance_type'
belongs_to :user
def emp_matches?(x)
(x.id.to_i == self.id.to_i ? true : false)
end
end
And this is my view..
<div class='row form-group'>
<div class='col-xs-8 col-xs-offset-2 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-2 col-lg-offset-5 text-right'>
<%= f.text_field :emp_id, tabindex: 1, id: 'emp_id', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>
</div>
</div>
<div class='row form-group'>
<div class='col-xs-8 col-xs-offset-2 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-2 col-lg-offset-5 text-right'>
<%= f.text_field :emp_first_name, tabindex: 1, id: 'emp_first_name', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>
</div>
</div>
My tables
Visual model
Table is called Employee
ID
emp_first_name
User model
Table is called User
emp_id
Fixed my question mark error...
def emp_matches(x)
(x.id.to_i == self.id.to_i ? true : false)
end
end
but I am still getting no method error
NoMethodError (undefined method `id' for nil:NilClass):
app/models/visual.rb:18:in `emp_matches'
app/controllers/user_controller.rb:31:in `populate_form'
I think you are over complicating this, and based on the information provided I don't think we need to concern ourselves the user model. you can do something like this
def populate_form
visual = Visual.find_by_id(params[:emp_id])
if visual
render :json => {
:emp_first_name => visual.first_name
}
else
render :json => { :error => 'not found' }
end
end
Then your javascript can do something if it finds the emp_first_name in the json response, or the error. I still don't see why the emp_matches part is needed?
First off here is my model, controller, view:
My model, this is where I have my search code:---------------------------
def self.find_by_lcc(params)
where = []
where << "category = 'Land'"
unless params[:mls].blank?
where << "mls = :mls"
end
unless params[:county].blank?
where << "county = :county"
end
unless params[:acreage_range].blank?
where << "acreage_range = :acreage_range"
end
unless params[:landtype].blank?
where << "landtype = :landtype"
end
unless params[:price_range].blank?
where << "price_range = :price_range"
end
if where.empty?
[]
else
find(:all,
:conditions => [where.join(" AND "), params],
:order => "county, price desc")
end
end
My controller:----------------
def land
#counties = ['Adams', 'Alcorn', 'Amite', 'Attala']
#title = "Browse"
return if params[:commit].nil?
#properties = Property.find_by_lcc(params)
else
'No properties were found'
render :action => 'land_table'
end
My View: ----------------------
<table width="900">
<tr>
<td>
<% form_tag({ :action => "land" }, :method => "get") do %>
<fieldset>
<legend>Search our Land Properties</legend>
<div class="form_row"><p> </p></div>
<div class="form_row">
<label for="mls">MLS Number:</label>
<%= text_field_tag 'mls', params[:mls] %>
</div>
<div class="form_row">
<label for "county"><font color="#ff0000">*County:</font></label>
<%= select_tag "county", options_for_select(#counties), :multiple => true, :size => 6 %>
</div>
<div class="form_row">
<label for "acreage_range">Acreage:</label>
<%= select_tag "acreage_range", options_for_select([['All',''],['1-10','1-10'],['11-25','11-25'],['26-50','26-50'],['51-100','51-100']]) %>
</div>
<div class="form_row">
<label for "landtype">Type:</label>
<%= select_tag "landtype", options_for_select([['All',''],['Waterfront','Waterfront'],['Wooded','Wooded'],['Pasture','Pasture'],['Woods/Pasture','Woods/Pasture'],['Lot','Lot']]) %>
</div>
<div class="form_row">
<label for="price_range"><font color="#ff0000">*Price:</font></label>
<%= select_tag "price_range", options_for_select([['All',''],['0-1,000','0-1,000'],['1,001-10,000','1,001-10,000'],['10,001-50,000','10,001-50,000'],['50,001-100,000','50,001-100,000'],['100,001-150,000']])%>
</div>
<input type="text" style="display: none;" disabled="disabled" size="1" />
<%= submit_tag "Search", :class => "submit" %>
</fieldset>
<% end%>
</td>
</tr>
</table>
The search works fine until I add ", :multiple => true, :size => 6" to make the county field multiple select. Then I get the error:
Processing PublicController#land (for 65.0.81.83 at 2010-04-01 13:11:30) [GET]
Parameters: {"acreage_range"=>"", "commit"=>"Search", "county"=>["Adams", "Amite"], "landtype"=>"", "price_range"=>"", "mls"=>""}
ActiveRecord::StatementInvalid (Mysql::Error: Operand should contain 1 column(s): SELECT * FROM `properties` WHERE (category = 'Land' AND county = 'Adams','Amite') ORDER BY county, price desc):
app/models/property.rb:93:in `find_by_lcc'
app/controllers/public_controller.rb:84:in `land'
/usr/lib/ruby/1.8/thread.rb:135:in `synchronize'
fcgi (0.8.7) lib/fcgi.rb:117:in `session'
fcgi (0.8.7) lib/fcgi.rb:104:in `each_request'
fcgi (0.8.7) lib/fcgi.rb:36:in `each'
dispatch.fcgi:24
I've tried to make the county, acreage_range, and price_range fields into multiple select boxes numerous ways, but can not get any method to work correctly. Any help would be greatly appreciated.
Thanks,
Try
unless params[:county].blank?
where << "county IN (:county)"
end
OR
unless params[:county].blank?
where << "county IN ( #{params[:county].join(',')})"
end
Try
unless params[:county].blank?
where << "county IN (:county)"
end
EDIT #1
I believe now it'll work even if the "ALL" option is selected
unless params[:county].blank? || params[:county] == "ALL"
where << "county IN (:county)"
end
EDIT #2
I thought the all option was in county. Try this:
unless params[:county].blank?
where << "county IN (:county)"
end
unless params[:acreage_range].blank? || params[:acreage_range] == "ALL"
where << "acreage_range = :acreage_range"
end
Hope it works now :]