This Map in Ruby doesn't care about my if statement - ruby-on-rails

So, I have this
def userposts
posts = Post.where(user_id: params[:id])
postnums = posts.map {|i| i.id }
postsWithInfo = posts.map{|i| {
post: i,
recipe: i.recipe,
recipepic: rails_blob_path(i.recipe.pic) if i.recipe?,
pics: i.pics.map{|p| rails_blob_path(p) }
}}
render json: {posts: postsWithInfo}, status: 200
end
recipe is null if there's no recipe, and that's what I want, but the problem is that recipepic is crashing the thing if i.recipe is null, and that if statement is doing nothing to stop it. Is there a way I can make it so that this works?
The error I get is
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:27: syntax error, unexpected `if' modifier, expecting '}'
...ails_blob_path(i.recipe.pic) if i.recipe?,
... ^~
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:27: syntax error, unexpected ',', expecting '}'
...ath(i.recipe.pic) if i.recipe?,
... ^
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:29: syntax error, unexpected '}', expecting `end'
}}
^

try this way
postsWithInfo = posts.map do |i|
{
post: i,
recipe: i.recipe,
recipepic: i.recipe? ? rails_blob_path(i.recipe.pic) : nil,
pics: i.pics.map{|p| rails_blob_path(p) }
}
end

Related

ruby on rails: multiple conditions in select array with hashes

This line works:
f = a.select{ |g| g['done']== 'false' }.select{ |g| g['subject'].include? "send" }.pluck('id','done','subject')
But this line
f = a.select{ |g| g['done']== 'false' && g['subject'].include? 'send' }
Does not. I get a
syntax error, unexpected '}', expecting `end'
... g['subject'].include? 'send' }
...
^
What's wrong with the code?

User Lower Function in where condition in searchkick

#ankane
How can i use postgres lower function in searchkick's where condition
I have below query which is working fine
klass.search(#params[:query], fields: [:name,:category_name],where: {or: [[{available_cities_name: "New Yo"},{available_cities_short_name: "NY"}]]}).hits
Now i want to use lower function but i am getting syntax error
klass.search(#params[:query],
fields: [:name,:category_name],
where: {
or: [ [
{"lower(available_cities_name) = ?", "New Yo"},
{"lower(available_cities_short_name) = ?", "ny"}
]]
}
).hits
I am getting below syntax error,
SyntaxError: unexpected '}', expecting end-of-input
e_cities_name) = ?", "New Yo"},{"lower(available_cities_shor
Can somebody tell me how to use lower function in searchkick ?
Elasticsearch does not have a lower function. To get around this, you can index a lowercase version of the field and query against that.
def search_data
{
available_cities_name: available_cities_name,
available_cities_name_lower: available_cities_name.downcase
}
end
There are two ways to pass args to part of your query. The first is to use hash-syntax eg: {arg_name: 'expected_value'} and the second is array-syntax: ["arg_name = ?", 'expected_value']
Your bug is that you are using array-syntax, but trying to pass it as a hash. ie: {"arg_name = ?", 'expected_value'} which is invalid syntax.
Instead try:
klass.search(#params[:query],
fields: [:name,:category_name],
where: {
or: [
["lower(available_cities_name) = ?", "New Yo"],
["lower(available_cities_short_name) = ?", "ny"]
]
}
).hits
or even just:
klass.search(#params[:query],
fields: [:name,:category_name],
where: ["lower(available_cities_name) = ? OR lower(available_cities_short_name) = ?", "New Yo", "ny"]
).hits
(Note: all code needs to be bug-tested before running).

Implicit return value and compile errors in ruby

Consider the following code in a class in ruby:
def isDarkSide
true
end
The return value of isDarkSide is true
However, when I run ruby -c on the following code:
def can_join_group? any
DeathStar::Tie::BOT, self, nil
end
I endup with the following errors:
dynamic constant assignment
DeathStar::Tie::BOT, self, nil
^
Can't change the value of self
DeathStar::Tie::BOT, self, nil
^
Can't assign to nil
syntax error, unexpected '\n', expecting '='
However, the problem can be fixed by writing
def can_join_group? any
return DeathStar::Tie::BOT, self, nil
end
Can someone explain to me why do I need to use the return keyword ? I feel like I'm missing something important in ruby language.
To return multiple values, you should use either explicit return or array of values.
Also 1, 2, 3 is not even a valid Ruby syntax.
def multi_return1
return 1, 2, 3
end
def multi_return2
[1, 2, 3]
end
multi_return1 == multi_return2
#=> true

looping from database and no implicit conversion of Symbol into Integer

I encounter a strange problem when trying to alter values from a Hash. I have the following setup:
def index
data, total = Role.with_filtering(params, current_holding_company)
data.each do |total_user|
total_user = { total_user: RoleUser.where(role_id: data[:id]).group(:user_id).count.to_s }
data[:total_user] = total_user
end
respond_to do |format|
format.json { render json: { data: data, total_count: total }.to_json, status: 200 }
end
end
When I execute this code I get: "TypeError: no implicit conversion of Symbol into Integer" . What am I doing wrong?
data is output from database, so my goal is i want to add total_user in every record with add new key and value into data
This might not completely solves your issue but hopefully will guide you to the correct path.
In ruby the error TypeError: no implicit conversion of Symbol into Integer usually happens when you miss treat an array!
lets suppose you have
numbers = [1,2,3]
#now
numbers[0]
# > 1
numbers[2]
# > 3
#But
numbers[:1]
# throws TypeError: no implicit conversion of Symbol into Integer
So, you must be passing a symbol on an array [] operator by mistake
One way to debug this kind of issues is by checking class type of your objects, something like this in the consol
data.class
# > Array (for example)
try this....
def index
data, total = Role.with_filtering(params, current_holding_company)
data.each do |total_user|
total_user = { "total_user" => RoleUser.where(role_id: data[:id]).group(:user_id).count.to_s }
data[:total_user] = total_user
end
respond_to do |format|
format.json { render json: { data: data, total_count: total }.to_json, status: 200 }
end
end

Skip `if` in case that statement is not possible

In my rails contoller I have this code:
if Photo.find(params[:photo_id]).patient_id == nil
.........
else
.........
So at the time I get a error when there are no params[:photo_id]:
Couldn't find Photo without an ID
I know that I could fix it with: For example:
if(params[:photo_id]) && (Photo.find(params[:photo_id]).patient_id == nil)
But now I tried to write an exception "how its called I think":
if Photo.find(params[:photo_id]).patient_id == nil rescue false
That throws a new error:
syntax error, unexpected modifier_rescue, expecting keyword_then or ';' or '\n' if
So what did a wrong?(I'm beginner in programming!)
You just need some parens.
if (Photo.find(params[:photo_id]).patient_id == nil rescue false)
...
end
The syntax is wrong. Try:
begin
if Photo.find(params[:photo_id]).patient_id == nil
.........
else
.........
rescue
false
end
Photo.find_by_id(params[:photo_id]).try(:patient_id)
Avoid using exceptions for situations that are not exceptional... and by the sounds of it, you're expecting to occasionally to have a Photo that doesn't get found.

Resources