LIKE statement but skips current post - ruby-on-rails

I'm trying to use the LIKE condition to find similar posts.
Here is my code:
#post = Post.find(params[:id])
#post_gsub = Post.find(params[:id]).name.gsub(/something|something else|something else again/, '')
#related_posts = Post.where("name LIKE '%#{#post_gsub}%'")
But when I pull this into the Rails view, there is currently always one match that shows up, which is the current blog post the user is on. How do I skip that current blog post so that "#related_posts" is only showing unique recommendations and not the post the user is currently on?

You can try chaining the where.not method Considering you're using Rails 3, you can use part of raw SQL:
Post.where('name LIKE ? AND id != ?', "%#{#post_gsub}%", #post.id)
That'll make your query to add a != operator to get every post other than the one with id equal to #post.id.

For rails 3 try
Post.where('name LIKE ? AND id != ?', "%#{#post_gsub}%", #post.id)

Related

Ruby on Rails beginner question : equality

I'm starting to know ROR and I was doing a kind of blog with articles, etc...
I did this code :
def show
id = params[:id]
list = Article.all
is_valid = false
list.all.each do |article|
if article.id == id
#is_valid = true
break
end
end
As you can see, this code just wants to check if the article ID exists or not. So I'm testing equality between id and article.id (which's a model linked to the appropriated table in the database) BUT when I try to use or display #is_valid boolean I saw that article.id == id is FALSE every time, even if article.id = 2 and id = 2. I tried to think about everything that can make this occuring, but I admit I still misunderstand this.
Then I ask you if you know why this is occuring. Of course, an equality like 2 == 2 will change #is_valid to true.
Thank you for your help !
Maybe its because params[:id] it's a string and article.id it's an Integer
(byebug) params
{"controller"=>"admin/my_controller", "action"=>"edit", "id"=>"1"}
And yes it is... "id" is a string "1", so you may try this:
def show
id = params[:id].to_i
list = Article.all
is_valid = false
list.all.each do |article|
if article.id == id
#is_valid = true
break
end
end
end
And maybe could work.
This is the answer to your question,
But if you want to learn a little more about Activerecord you can do this
Article.exists?(params[:id])
and that will do what you are trying to do just with a query against db.
and if you want to get just a simple article
record = Article.find_by(id: params[:id]) #return nil when not exist
if record # if nil will threat like false on ruby
#my code when exist
else
#my code when not exist
end
will work (you also can use find but find will throw an exception ActiveRecord::RecordNotFound when not exists so you have to catch that exception.
Activerecord has many ways to check this you dont need to do it by hand.
def show
#article = Article.find(params[:id])
end
This will create a database query which returns a single row. .find raises a ActiveRecord::NotFound exception if the record is not found. Rails catches this error and shows a 404 page. Article.find_by(id: params[:id]) is the "safe" alternative that does not raise.
Your code is problematic since list = Article.all will load all the records out of the database which is slow and will exhaust the memory on the server if you have enough articles. Its the least effective way possible to solve the task.
If you want to just test for existence use .exists? or .any?. This creates a COUNT query instead of selecting the rows.
Article.where(title: 'Hello World').exists?

Rails - update multiple active record relations

I am doing an update all to a Model to update several ActiceRecord Relations.
But I want to skip an attribute if its not provided (if its nil or empty I dont want to update that attribute)
def update_numbers(numbers, comment)
numbers.update_all (number_status: Number::STATUS_UPDATED, comment: comment if void_comment.present?)
end
This obviously does not work as it doesn't like the if condition. Is there a way to not try and update comment if its .blank?
Does this work for you?
def update_numbers(numbers, comment)
hash = { number_status: Number::STATUS_UPDATED }
hash[:comment] = comment if comment.present?
numbers.update_all hash
end

Displaying from my database

I'm new to rails and I'm working on a project where I'm having an issue. I'm trying to display all the gyms that have the same zipcode. When I tried the code below, it only displays 1 and not the other ones. How can display all the gym that have the same zip code?
controller
def gym
#fitness = Fitness.find_by(zip_code: params[:zip_code])
end
gym.html.erb
<%= #fitness.name %>
You're doing this to yourself. By definition, #find_by only returns a single record, or nil. You probably want #where instead:
Fitness.where(zip_code: params[:zip_code])
If that still doesn't work, check both your table data and the content of your params hash to make sure you're creating a valid query.
def gyms
#fitness = Fitness.where("zip_code = ?", params[:zip_code])
end

Rails - submitting JSONs to database from controller

I am working on a Rails app, and I am attempting to insert attributes from JSONs as database entries. I'm running into a problem, though, and would appreciate some guidance.
I've been able to jam a few things together and come up with something that sort of works...
def create
#report_group = Array.new
#report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})
#report_group.each do |x|
#new_report = Report.new(x)
#new_report.user_id = current_user.id
#new_report.save
end
end
private
def report_params(params)
params.permit(:user_id,:location,:comments)
end
This is a good first step - this commits two entries to my database, one for each of the hashes pushed into #report_group, but it is suffering from a problem - the create action does not reference the report_params whitelist.
I have built several Rails apps where entries are submitted one at a time via the standard Rails form helpers, but I have never done it with multiple JSONs like this before. Trying out the syntax I'd use in a typical form helper situation
#new_report = Report.new(report_params(x))
throws the expectable error undefined method permit' for #<Hash:0x007f966b35e270> but I am not sure what else to do here.
EDIT TO SHOW SOLUTION
Big thanks to #oreoluwa for pointing me in the right direction. Here's the solution that I came up with.
def create
#report_group = Array.new
#report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})
#report_group.each do |x|
hash = ActionController::Parameters.new(x)
#new_report = Report.new(report_params(hash))
#new_report.user_id = current_user.id
#new_report.save
end
end
private
def report_params(params)
params.permit(:user_id,:location,:comments)
end
You're getting the error because a Hash is not the same as an ActionController::Parameters. In order to use the permit method with your Hash you may need to first convert it to ActionController::Parameters, as such:
hash = {location:"home", comments:"Hello, database!"}
parameter = ActionController::Parameters.new(hash)
parameter.permit(:user_id,:location,:comments)
I don't know if that is what you're looking for, but I thought to point you in the right direction.

How to update an active record in ruby

I want to update status to 1, when user views a message.
i need an active record, to change status to 1 ,where status is 0 and id is current id
Any help is appreciated.
i want to change this query to active record.
UPDATE 'course_queries SET status = '1' WHERE course_queries.id =41 and status=0;
As Nithin mentioned, ActiveRecord is a rails feature. Thus, the following wouldn't work unless you're using the Ruby on Rails framework.
With that said, you could also try:
#course = CourseQuery.where(id: params[:id], status: 0).each do |q|
q.update(status: 1)
end
If you need it all in one line, you could use:
#course = CourseQuery.where(id: params[:id], status: 0).update_all(status: 1)
You can then change the id or status here dynamically. :)
Since these examples use the update and update_all methods, I'd recommend you read up about them. Here's a great article I've found on the differences: Difference between active record methods – update, update_all, update_attribute, update_attributes
Something like this
Using ActiveRecord.
#course_query = CourseQuery.find(params[:id]) #id is 41 from your comment
if #course_query.status == 0
#course_query.status = 1
#course_query.save
end

Resources