Update a record in a table in rails - ruby-on-rails

I have a table A(:name, :flag) and want to update the flag column of a record in the table if a certain condition evaluates to true.
if A.find(300).flag == false
//Will this work -> A.find(300).flag = true
What should I write in that line?

if A.find(300).flag == false
//Will this work -> A.find(300).flag = true
change to
A.find(300).update(flag: true) if A.find(300).flag == false
You can add method to a.rb
def self.update_if_false id
find(id).update(flasg: true) if A.find(id).flag == false
end
Then you can use it as A.update_if_false(300)

This will decrease database call if flag is true:
Rails 4:
obj = A.find(300)
obj.update(flag: true) unless obj.flag
Rails 3.2:
obj = A.find(300)
obj.update_attributes(flag: true) unless obj.flag
Note: update method made public and aliased with update_attributes in active record 4.

yes..it will work...i tried in ruby2.0 console..Assuming you have all the attributes present....
2.0.0-p481 :026 > Image.find(30).title = true
Image Load (7.8ms) SELECT "images".* FROM "images" WHERE "images"."id" = $1 LIMIT 1 [["id", 30]]
=> true
you can go ahead and add your update statement ..if true else false.
if A.find(300).flag == false
##do something
else
##do other thing
end

Related

how can i get a single result from a database function in ruby on rails?

I am trying to fetch the result of a database function to store it in a variable. In the case of this function, a receipt id is passed and the function returns TRUE or FALSE depending on whether the receipt is enabled. Try in the following ways:
result = ActiveRecord::Base.connection.execute("SELECT receipt_enabled FROM schema.receipt_enabled(158800)")
=> #<PG::Result:0x00556c7c374158 #connection=#<PG::Connection:0x00556c7d8ab3f0 #socket_io=nil, #notice_receiver=nil, #notice_processor=nil>>
result = ActiveRecord::Base.connection.execute("SELECT receipt_enabled FROM schema.receipt_enabled(158800)").to_a
=> [{"receipt_enabled"=>"f"}]
result = ActiveRecord::Base.connection.select_all("SELECT receipt_enabled FROM schema.receipt_enabled(158800)").rows
=> [["f"]]
I would need to do something similar to this
if result == true
#showreceipt = true
else
#showreceipt = false
end
ActiveRecord::Result has cast_values method (it uses deserialize under the hood)
query =
<<~SQL
SELECT receipt_enabled
FROM schema.receipt_enabled(158800)
SQL
ActiveRecord::Base.connection.exec_query(query).cast_values.flatten.first
# will return true or false

Can't use where on a column with nil value

I have an Article model
Article.last.publish
=> nil
Article.last.publish != true
=> true
Article.where("publish != ?", true)
=> []
Why am I getting an empty array there?
There are only 2 falsy values in ruby : false and nil
So, if you check the value of !nil then the output will be true
So with your first statement
Article.last.publish # its output is nil
Then your second statement
Article.last.publish != true # this is correct , since !nil = true
But the last one
Article.where("publish != ?", true)
gets converted into a query as
SELECT `articles`.* FROM `articles` WHERE (publish != 1)
which means all articles whose publish value is not true, which means false
and false is not equal to nil.
nil and false are two different falsy values.
Try Article.where(publish: false)

'validate_inclusion_of' isn't working

I need to set a condition where, if my_counter is equal to 0, 1 or 2, then my validation flag is set to true, otherwise set my validation flag to false.
But my validate_inclusion_of call isn't working:
if User.find_by_email(#email)
user = User.find_by_email(#email)
user.my_count += 1
user.save
# Here is where it fails
if validates_inclusion_of :my_count, :in => [0,1,2]
#my_flag = true
else
#my_flag = false
end
That is not how you setup validations on models. May I suggest you do this:
#my_flag = [0,1,2].include? user.my_count
Edit: let me point out that you are finding your User twice which results in 2 queries. Consider doing this:
if user = User.find_by_email(#email)
user.my_count += 1
user.save
#my_flag = [0,1,2].include? user.my_count
end

Return false statement

I'm new to RoR; I want create the following statement. I've an array; I want that controller return false if all array elements are not equal to a variable value.This is the code
def check_warehouse(asset,serial)
wh = Warehouse.where(["(asset = ? and serial = ?) OR (asset = ?) OR (serial= ?)",asset,serial,asset,serial])
return false if wh.count > 1
return false if
wh.each do |wh|
wh.position_id != session[:position_id]
end
end
but it doesn't works!why?
Moreover, can you suggest me a plugin or gem running on Rails 3.1 for generate pdf from RoR datas?
Thank you all
You have this code:
return false if wh.each do |wh|
wh.position_id != session[:position_id]
end
This will not execute the way you want. In ruby, .each will execute the "block" (code between do/end) and return to you the original array.
So if wh is an array, empty or not, and you say:
return false if []
ruby will not return false. instead, you'd likely rather:
return false if wh.any? {|wh| wh.position_id != session[:position_id] }
You probably would want it to return true if the position is the session position, so you can switch to:
return wh.any?{|wh| wh.position_id == session[:position_id] }
Try smth like this:
def check_warehouse(asset,serial)
wh = Warehouse.where(["(asset = ?) OR (serial= ?)",asset,serial]) # first condition was just extra
return false if wh.detect {|wh| wh.position_id != session[:position_id] }
end
I removed return false if wh.count > 1 because there's no sense to check the array if you return if it has more than 1 element. Please tell me if I misunderstood you
UPD
Actually you can do that in the db:
def check_warehouse(asset,serial)
Warehouse.where(
["(asset = ? OR serial= ?) AND NOT position_id = ?", asset, serial, session[:position_id]]
).count.zero?
end

How do I create a query that sets true if one or more records exist?

I want to create a query like so:
#step1_completed = IF 1 or more records exists return true, else false
The exist? method was made for this:
Record.exist?
It will do a query to check if a single record for the table exists and will return true if it does.
Assuming record is a model,
#step1_completed = Record.any?
How about the following:
#step1_completed = Record.first ? true : false

Resources