IF conditions in rails is not executing - ruby-on-rails

I'm trying to do solr search based on the text entered by the user. Firts I've to check whether the entered text is store or brand or category. After checking that condition I want to display corresponding riesults which are in the MainNavigationUrls table using solr search. Here is the controller action. It is working fine if I enter any store and can get proper results. But it is not going inside brands loop if the storesearch is found nill. Please explain why it is not executing the second case.
def search_all
#storesearch=Site.search do
fulltext params[:text]
with(:multibrand,1)
end
if(#storesearch.nil?)
#brandsearch=Brand.search do
fulltext params[:text]
end
if(#brandssearch.nil?)
#itemcategorysearch=MainCategory.search do
fulltext params[:text]
end
#itemcategorysearch.results.each do |result|
#itemcategorysearch1=MainNavigationUrl.search do
with :main_categoty_id, result.id
with :department_id, params[:deptid].to_i
paginate :page=>params[:page], :per_page=>45
end
end
else
#brandsearch.results.each do |result|
#brandsearch1=MainNavigationUrl.search do
with :brand_id, result.id
with :department_id, params[:deptid].to_i
paginate :page=>params[:page], :per_page=>45
end
end
else
#storesearch.results.each do |result|
#storesearch1=MainNavigationUrl.search do
with :site_id, result.id
with :department_id, params[:deptid].to_i
paginate :page=>params[:page], :per_page=>45
end
end
end
end

instead of .nil? ,maybe you can use .blank? is better?
#array = []
#array.nil? -false
#array.blank? -true
I think you are checking if #storesearch contain some elements?

Related

How can i make this generic and make all the available attribute as filtering params?

I have multiple controllers. and I have a method to filter like this.
def filter(filtering_params)
results = where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
and from controllers, I will call index or show APIs using filtering params for example like this.
def filtering_params
params.slice(:status, :created_at, :id, :transaction_datetime, :portfolio_external_reference_id, :file_id, :file_name)
end
which I will use while fetching from API like this.
def index
records = Module::Class.filter(filtering_params)
render json: {
data: records
}
end
I want to write a generic method that can be used in cases where I want all the available attributes in the particular model as the filtering_params. is there any better way than writing all the attributes?
I solved it and it's working for me.
def filter_params(params)
values = params.slice(*column_names.map(&:to_sym))
filter(values)
end

ActiveRecord query alias field name output in jBuilder

Hi I am new to ruby on rails development. This is my controller function query
def index
#questions = Question.order('questions.created_at DESC').joins('left join favourites on questions.id=favourites.question_id and favourites.user_id='+current_user_id.to_s).includes(:user).select('CASE WHEN favourites.user_id='+current_user_id.to_s+' THEN 1 ELSE 0 END as favour').references(:favourite).page(params[:page]).per( (ENV['ILM_QUESTIONS_PER_PAGE'] || 15).to_i )
end
From this query i dont know how to get the value for "favour" column in select query.
This is my jbuilder file in views
/index.json.builder
json.number_of_items_per_page #questions.length
json.total_number_of_pages #questions.total_pages
json.user_favour #questions.favour
json.questions do
json.array! #questions do |question|
json.partial! 'api/v1/questions/question', question: question,include_comments: false
end
end
/_question.json.builder
json.id question.id
json.content question.content
json.created_at question.created_at
json.image_url question.image.url
when i put #questions.favour in index.json.builder
i got this error
undefined method `favour' for #<Question::ActiveRecord_Relation:0x0000000c39b5f0>
Please Advice me on this issue
Thanks in Advance.

Rails 3: Search method returns all models instead of specified

What I'm trying to do: I have a model "Recipe" in which I defined a method "search" that takes an array of strings from checkboxes (I call them tags), and a single string. The idea is to search the db for recipes that has anything in it's 'name' or 'instructions' that contains the string, AND also has any of the tags matching it's 'tags' property.
Problem: The search method return all the recipes in my db, and doesn't seem to work at all at finding by the specific parameters.
The action method in the controller:
def index
#recipes = Recipe.search(params[:search], params[:tag])
if !#recipes
#recipes = Recipe.all
end
respond_to do |format|
format.html
format.json { render json: #recipe }
end
end
The search method in my model:
def self.search(search, tags)
conditions = ""
search.present? do
# Condition 1: recipe.name OR instruction same as search?
conditions = "name LIKE ? OR instructions LIKE ?, '%#{search[0].strip}%', '%#{search[0].strip}%'"
# Condition 2: if tags included, any matching?
if !tags.empty?
tags.each do |tag|
conditions += "'AND tags LIKE ?', '%#{tag}%'"
end
end
end
# Hämtar och returnerar alla recipes där codition 1 och/eller 2 stämmer.
Recipe.find(:all, :conditions => [conditions]) unless conditions.length < 1
end
Any ideas why it return all records?
if you are using rails 3, then it is easy to chain find conditions
def self.search(string, tags)
klass = scoped
if string.present?
klass = klass.where('name LIKE ? OR instructions LIKE ?', "%#{string}%", "%#{string}%")
end
if tags.present?
tags.each do |tag|
klass = klass.where('tags LIKE ?', "%#{tag}%")
end
end
klass
end
When you do
search.present? do
...
end
The contents of that block are ignored - it's perfectly legal to pass a block to a function that doesn't expect one, however the block won't get called unless the functions decides to. As a result, none of your condition building code is executed. You probably meant
if search.present?
...
end
As jvnill points out, it is in general much nicer (and safer) to manipulate scopes than to build up SQL fragments by hand

Setting default search parameter on Ransack for rails

I've been wracking my brain over this but can't get it. I feel like the answer is probably obvious.
What I'm trying to do is the following:
I have an index controller which lists a series of Jobs which I can search using Ransack. Each job has a completion date which either has a date in it or is null (unfinished). Currently, the search itself works great. I would like to make it so that the index page loads up showing only the unfinished work, but I also want it to work so that when someone does run a search, returns results for both finished and unfinished work.
Any help would be greatly appreciated. In the code below, :actual is the name of the field with the completion date. I also was looking around the web and thought that maybe something like the DEFAULT_SEARCH_PARAMETER={} that I have in the Job model might work but I couldn't seem to get it to.
Here is the code:
class Job < ActiveRecord::Base
DEFAULT_SEARCH_PARAMETER ={}
attr_accessible :items_attributes, :actual
end
def index
#search = Job.search(params[:q] || Job::DEFAULT_SEARCH_PARAMETER)
#search.build_condition
#results = #search.result
#job = #results.paginate(:per_page => 10, :page => params[:page])
end
Late to the party, but thought I'd suggest an alternate approach in case someone else comes across this.
The answer above works, but its disadvantage is that the default is not added to Ransack's search object, so - if you are using a search form - the default selection is not shown in the form.
The following approach adds the default to the search object and therefore will appear in your search form.
def index
#search = Job.search(params[:q])
#search.status_cont = 'Open' unless params[:q] #or whatever, must use Ransack's predicates here
#results = #search.result
#job = #results.paginate(:per_page => 10, :page => params[:page])
end
I think you could just apply your own filter when the search parameters don't exist:
def index
#search = Job.search(params[:q])
#results = #search.result
#results = #results.where(:your_date => nil) unless params[:q]
#job = #results.paginate(:per_page => 10, :page => params[:page])
end
Many years later I found myself with this exact problem so I thought I'd chime in with a solution I'm using. Set default search params in the controller and reverse merge them into params[:q]:
def index
default_search_params = {
status_cont: "open"
}
#search = Job.search((params[:q] || {}).reverse_merge(default_search_params))
...
end
So by default, you want the page to load with records where actual is nil. And later when the user searches you want to go back to how your search was working before.
Give this a try.
def index
#search = Job.search(params[:q] || Job::DEFAULT_SEARCH_PARAMETER)
#search.build_condition
#results = #search.result
if #results.nil?
#results=Job.find(:all, :conditions => ["actual = NULL"] )
end
#job = #results.paginate(:per_page => 10, :page => params[:page])
end

Using :includes with variables and further queries

Here's a query:
#projects = #user.projects.includes(:company => :workers)
In my view, I want to order a list of these projects by the tags that belong to the company.
So, projects belonging to the company's urgent tag come first, then elevated, then all others.
I think one way to do this is to define #companies, then define:
#urgent = #companies.tagged_with('urgent')
#elevated = #companies.tagged_with('elevated')
#others = #companies.tagged_with('urgent', 'elevated', :exclude => true)
# view:
#urgent.each do |u| ... end
#elevated.each do |e| ... end
#others.each do |o| ... end
1. How do I get #companies in the first place?
How can you collect all the companies together when the first query is the one I showed at the top? #companies = #projects.collect{|p| p.company} produces a non-searchable array.
2. Is there a more elegant way of displaying the projects than doing three loops?
I dont think you can do this without using 2 queries.
#projects = #user.projects.includes(:company => :workers)
#companies = Company.find(#projects.collect(&:id))
As for rendering the tags, you could do:
ordered_tags = ['urgent', 'elevated']
ordered_tags.each do |tag|
#companies.tagged_with(tag).each do |company|
my_render_logic
end
end
#companies.tagged_with(*ordered_tags, :exclude => true).each do |company|
my_render_logic
end

Resources