I am trying to do this using SQL in Ruby:
SELECT number*2 FROM dictionary;
I can use .select(:number) to get the number columns "as is", but I have no idea how to return them modified. I tried this (which obviously didn't work):
current_table.select(:number*2)
Try either of these
#newnumber = number.find(:all, :conditions => ["id = ?", #dictionary.id], :select => "number * 2 as newnumber")
#newnumber = number.all(:conditions=>"id='#{#dictionary.id}'",:select=>"number * 2 as newnumber")
Related
I have a query which I am trying to convert into yii2 syntax. Below is the query
SELECT project_id, user_ref_id FROM
(
SELECT `project_id`, `user_ref_id`
FROM `projectsList`
WHERE user_type_ref_id = 1) AS a WHERE user_ref_id = '.yii::$app->user->id;
I am trying to convert it into yii2 format like
$subQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from('projectsList')->where(['user_type_ref_id' => 1]);
$uQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from($subQuery)->where(['user_ref_id ' => yii::$app->user->id])->all();
It is giving an error like
trim() expects parameter 1 to be string, object given
How to I pass subquery as table name to another query
Not tested, but generally this is how it goes. You need to pass the subQuery as a table. So change ->from($subQuery) in the second query to ->from(['subQuery' => $subQuery])
$subQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from('projectsList')->where(['user_type_ref_id' => 1]);
Then
$query = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from(['subQuery' => $subQuery])->where(['subQuery.user_ref_id ' => yii::$app->user->id])->all();
I want to get all PartitionStates by name where it exactly meets the partitionName or starts with it when containing a ..
This is the query I have
return session.QueryOver<PartitionState>()
.Where(p => p.Name == partitionName)
.WhereRestrictionOn(p => p.Name).IsLike(partitionName + ".", MatchMode.Start)
.OrderBy(p => p.StartDate).Desc
.Take(1)
.SingleOrDefault<PartitionState>();
The above query produces an AND expression, but i want it to be an OR.
In SQL it should look like this:
SELECT TOP 1 *
FROM PartitionState
WHERE (Name = #partitionName OR Name like #partitionName+'.%')
ORDER BY StartDate DESC
It seems there is no built in method, but it is possible to pass a restriction into where method.
return session.QueryOver<PartitionState>()
.Where(Restrictions.Or(
Restrictions.Where<PartitionState>(p => p.Name == partitionName),
Restrictions.On<PartitionState>(p => p.Name).IsLike(partitionName + ".", MatchMode.Start)))
.OrderBy(p => p.StartDate)
.Desc.Take(1)
.SingleOrDefault<PartitionState>();
I have a simple form, where I set up a query that I want to browse, for example panasonic viera.
This is on how I search the term in database:
Product.where("name ilike ?", "%#{params[:q]}%").order('price')
The query looks like %panasonic viera%, but I would need to search the query this way: %panasonic%viera% - I need to find all products, where is in the title the word panasonic or viera... but how to make this query?
One solution would be to break up your query into individual terms and build a set of database queries connected by OR.
terms = params[:q].split
query = terms.map { |term| "name like '%#{term}%'" }.join(" OR ")
Product.where(query).order('price')
If you're using PostgreSQL, you can use pg_search gem. It's support full text search, with option any_word:
Setting this attribute to true will perform a search which will return all models containing any word in the search terms.
Example from pg_search:
class Number < ActiveRecord::Base
include PgSearch
pg_search_scope :search_any_word,
:against => :text,
:using => {
:tsearch => {:any_word => true}
}
pg_search_scope :search_all_words,
:against => :text
end
one = Number.create! :text => 'one'
two = Number.create! :text => 'two'
three = Number.create! :text => 'three'
Number.search_any_word('one two three') # => [one, two, three]
Number.search_all_words('one two three') # => []
How about via ARel
def self.search(query)
words = query.split(/\s+/)
table = self.arel_table
predicates = []
words.each do |word|
predicates << table[:name].matches("%#{word}%")
end
if predicates.size > 1
first = predicates.shift
conditions = Arel::Nodes::Grouping.new(predicates.inject(first) {|memo, expr| Arel::Nodes::Or.new(memo, expr)})
else
conditions = predicates.first
end
where(conditions).to_a
end
This isn't working?
WHERE name LIKE "panasonic" OR name LIKE "viera"
Here is the original logic
(scrape_datas = ScrapeData.find(
:all, :conditions =>
"artist_status = 'NOT_FOUND'
AND blacklisted = 1
AND extracted = 0
and not EXISTS(
SELECT * FROM artist_name_suggestions where original = artist_name
)
I've been able to split up the first part better
scrape_datas = ScrapeData.where(
:artist_status => 'NOT_FOUND',
:blacklisted => 1,
:extracted => 0
)
Although having issues getting the "and not EXISTS" query into the mix
and not EXISTS(
SELECT * FROM artist_name_suggestions where original = artist_name
)
Thanks!
Firstly you can extract simple scopes:
scope :not_found, where(:artist_status => 'NOT_FOUND')
scope :blacklisted, where(:blacklisted => 1)
scope :extracted, where(:extracted => 0)
Then add a query method (assume artist_name is a column of scrape_datas):
def self.no_suggestions
scrape_datas = ScrapeData.arel_table
suggestions = ArtistNameSuggestion.arel_table
where(ArtistNameSuggestion.where(
suggestions[:original].eq(scrape_datas[:artist_name])
).exists.not)
end
Now you can do something like this:
ScrapeData.not_found.blacklisted.extracted.no_suggestions
I can't find a working solution for the following piece of code:
def search_last_rate
self.rate = Rate.find(:first, :select => "rateconverted", :conditions => ["dominant_id = ? and converted_id = ?", self.currency_bought_iso, self.currency_sold_iso], :order => 'ratedate, dateloaded, timeloaded DESC')
end
When I execute this in the console I retrieve the appropriate value:
`=> #<Rate rateconverted: 0.8131>`
All columns are defined in MYSQL2 as an decimal but when I'm using it in the model and new html page it's always saving the value 0.0.
Please advice :)
decimal and integer are different in mysql. if u want the data to be numeric then use 'integer' in migrations else 'float'. checkout Decimal VS Int in MySQL?
Make sure that self.rate is not an integer
Try
self.rate = Rate.find(:first, :select => "rateconverted", :conditions => ["dominant_id = ? and converted_id = ?", self.currency_bought_iso, self.currency_sold_iso], :order => 'ratedate, dateloaded, timeloaded DESC').to_f