How to update table using "beans" - redbean

How do I convert this query to redbeans?
update trips set title="test" where title="Rome 9 days"
I know I cand do R:: exec () but I am wondering if it's the only way.

$bean = R::findOne('trips', 'title = ?', array('Rome 9 days'));
$bean->title = "test";
R::store($bean);
This should work

Related

ActiveRecord update_column: How to increase a record value depending on it's current value with just one query

The below hits database twice - how do I reduce it to single query?
#user = User.find(123)
#user.update_column(:views, #user.views + 1)
Something like this:
User.find(123).update_column(:views, self.views + 1)
User.where(id: 123).update_all('views = views + 1')
It will produce the following query:
UPDATE users SET views = views + 1 WHERE users.id = 123
Rails has a dedicated method increment_counter to increment a numeric field by one:
User.increment_counter(:views, 123)
# UPDATE `users` SET `views` = COALESCE(`views`, 0) + 1 WHERE `users`.`id` = 123
COALESCE(`views`, 0) ensures that it also works with NULL.
User.connection.execute(%|
UPDATE users SET views = views + 1 WHERE id = 123
|)
User.find(123).increment(:views)
see
http://apidock.com/rails/ActiveRecord/Base/increment
http://apidock.com/rails/ActiveRecord/Base/increment!

PG error using rails where

I have simple query like
User.where('(zone_id IN (?) AND zone_type = "Org") OR (zone_id = ? AND zone_type ="Com")', [1,2,3], 10)
This throws me
PG::UndefinedColumn: ERROR: column "Org" does not exist
What am i doing wrong?
Apparently replacing all conditions fixes the problem:
User.where('(zone_id IN (?) AND zone_type = "?") OR (zone_id = ? AND zone_type ="?")', [1,2,3], "Org", 10, "Com")
I would suggest following solition, which is more readable:
User.where(zone_id: [1,3,5] AND zone_type:"org").or.where(zone_id: 10 AND zone_type: "com")
More Rails way,
You don't have to use IN operator
User.where(zone_id: [1,3,5] AND zone_type:"org").or.where(zone_id: 10 AND zone_type: "com")

Sort by specific ids in ActiveRecord

I have inherited another programmer's Rails3 project, and I'm fairly new to rails overall. He's got a query that appears to sort by specific id's. Can somebody explain how this resolves in actual SQL? I think this code is killing the db and subsequently rails. I've tried to output it in the logger but can't seem to get the actual SQL to output even with config set to :debug. Searching heavily here (on SO) didn't turn up a clear explanation of how this query looks. The code looks like:
options = {
select: "SUM(1) AS num_demos, product_id ",
group: "product_id",
order: "num_demos ASC",
}
product_ids = Demo.where("state = 'waitlisted'").find(:all, options).collect{|d| d.product_id}
sort_product_ids = product_ids.collect{|product_id| "id = #{product_id}"}
Product.where(visible: true, id: product_ids).order(sort_product_ids.join(', '))
As far as I can see, the final line will create a query against the product table with an ORDER BY "id = 1, id = 3, ..." etc, which doesn't make a lot of sense to me. All clues appreciated.
A quick breakdown of what's going on, as it'll help you understand what to do for your replacement query.
options = {
select: "SUM(1) AS num_demos, product_id ",
group: "product_id",
order: "num_demos ASC",
}
product_ids = Demo.where("state = 'waitlisted'").find(:all, options).collect{|d| d.product_id}
This line will generate
SELECT SUM(1) as num_demos, product_id FROM "demos" WHERE (state = 'waitlisted') GROUP BY product_id
And returns an array of Demo objects, sorted by the count(*) of rows in the group, where only the product_id attribute has been loaded, and is available to you.
Next,
sort_product_ids = product_ids.collect{|product_id| "id = #{product_id}"}
results in a collection of product_ids mapped to the format "id = x". IE: If the previous result returned 10 results, with product_ids ranging from 1..10, sort_product_ids is now equivalent to ["id = 1", "id = 2", "id = 3", "id = 4", "id = 5", "id = 6", "id = 7", "id = 8", "id = 9", "id = 10"]
Finally,
Product.where(visible: true, id: product_ids).order(sort_product_ids.join(', '))
Selects all Products where the column visible is true, and their id is in the array of product_ids (which, as we found out earlier, is actually an array of Demo objects, not integers - this might be causing the query to fail). Then, it asks SQL to sort that result list by the sort_product_ids (sent in as a string "id = 1, id = 2, ... id = 10" instead of an array ["id = 1", "id = 2", ... "id = 10"]).
More info available at:
http://guides.rubyonrails.org/active_record_querying.html
http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html
To select and sort by a given array of ids you can use this
Product.where(visible: true, id: product_ids)
.order( "field(id,#{product_ids.join(',')})" )
If you are using PostgreSQL, consider to use WITH ORDINALITY, it is the fastest way compared to others. See this thread.
To apply this method to Ruby on Rails, for example:
class SpecifiedByIds
def specified_by_ids(ids)
joins(
<<~SQL
LEFT JOIN unnest(array[#{ids.join(',')}])
WITH ORDINALITY AS t(id,odr) ON t.id = #{table_name}.id
SQL
).order('t.odr')
end
end
class MyModel < ActiveRecord::Base
extend SpecifiedByIds
end

how to convert sql query in ruby and rails?

SELECT A.FirstName, A.LastName, B.PatientId, B.RoomNumber, B.AdmissionDate, B.DischargeDate, B.MeasureCategory
FROM DimPatient A, DimPatientStay B
WHERE A.Id = B.PatientId AND A.FirstName = 'Anuj' AND B.MeasureCategory = 'ED'
hi some updation for this
i solved this prob by
MODELNAME.find_by_sql("your sql query")
You can try this to find the result from sql query in Rails
query_params = Hash.new
sql_query = "SELECT A.FirstName, A.LastName, B.PatientId, B.RoomNumber, B.AdmissionDate, B.DischargeDate, B.MeasureCategory
FROM DimPatient A, DimPatientStay B
WHERE A.Id = B.PatientId AND A.FirstName = :first_name AND B.MeasureCategory = :measure_category"
query_params[:first_name] = first_name
query_params[:measure_category] = measure_category
#query_results = ActiveRecord::Base.connection.select_all(
ActiveRecord::Base.send("sanitize_sql_array",[sql_query, query_params] )
)
I guess you could try:
ActiveRecord::Base.connection().execute(#your_sql_here)
Suppose A is one class and B is another, you should use includes as following:
A.includes(:b).where(...) # add you condition in where
I suggest to check good video tutorials of ActiveRecord here

Ruby - Splititng Array after getting data from Mysql

I have the following code to fetch the data from MySQL database into my rails controller
#main = $connection.execute("SELECT * FROM builds WHERE platform_type IS NOT NULL")
This returns a mysql2 type object which behaves like an array i guess.
I want to split this into 2 arrays, first one where platform_type is 'TOTAL' and everything else in the other array.
It actually returns a Mysql2::Result object. Of course you can do
totals = []
others = []
main.each { |r|
(r['platform_type'] == 'TOTAL' ? totals : others) << r
}
but why not use a rails way with smth like:
Builds.where("platform_type = ?", 'TOTAL')
Builds.where("platform_type NOT IN ?", [nil, 'TOTAL'])
Try array.select. Something like
total = #main.select { |build| build.platform_type == 'TOTAL' }
not_total = #main.reject { |build| build.platform_type == 'TOTAL' }
http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/
Even better, use Enumerable.partition as per this answer: Ruby Select and Reject in one method

Resources