getting a column by "name" in an activerecord - ruby-on-rails

I have a select statement that returns a field in a table.
records = Product.select("DISTINCT #{iFieldName}").where("id in (0, #{iInClaws})" )
I want to convert the data in the database to an array to be used later.. say as another inClaws.
records.each{|record| fieldArray << record.?????}
I have two questions.
Is there a better way to do this?
If there's not, then how do I get the data out of the field.
Thanks to all..
After everyone came to help my final method looked like this.
def self.getFieldArray(iFieldName, iIDsInClaws, iIdFieldName = 'id')
records = self.select("DISTINCT #{iFieldName}").where("#{iIdFieldName} in (#{iIDsInClaws})" )
return records.map{|record| record.send(iFieldName)};
end

fieldArray = records.map(&:iFieldName)
Or
res = records.map{|r| r.send(iFieldName)}

records.each{|record| fieldArray << record.send(iFieldName)}

Related

Rails subquery always returns nil value

I need to count rows from other table in subselect, so I use this query:
follows_sql = Follow.where(followable_type: 'Idea').where('follows.followable_id = ideas.id').select('COUNT(followable_id)').to_sql
idea = Idea.select("(#{follows_sql}) AS fcnt").includes(:collaborations).
where(collaborations: { user_id: 4, owner: true })
So its produced valid SQL, but I cant access 'fcnt' value from idea var. I tried do it in different ways like:
idea[0].fcnt # return nil
idea[0]["fcnt"] # return nil
But I only can access fields which exists in a Idea model.
How I can access my custom 'fcnt' field?
I think something along the following should work for you
idea = Idea.select("ideas.*, COUNT(follows.id) AS fcnt").joins("LEFT OUTER JOIN follows ON follows.followable_id = ideas.id").group("ideas.id")
ideas.each do |idea|
puts idea.fcnt
# Should output a number
end
Note that I've left out the other includes and where clauses. Try to solve the problem first, and if this query works out, then add in your additional clauses.
Also, if you setup your relations correctly, such that an idea has many follows, you could clean up your code by doing something like
ideas = Idea.includes(:collaborations).where(collaborations: { user_id: 4, owner: true })
ideas.map { |idea| idea.follows.count }

Simplifying an expression using .map

Below I have an example active record query using a bunch of each iterators
user.user_spells.each do |us|
us.spell.buff_effects.where(stat_effected:'gold').each do |be|
value = value + be.value
end
end
I would like to use .map to return a list of all the results so I can do it essentially in one line.
I came up with:
user.user_spells.map { |us| us.spell.buff_effects.where(stat_effected:stat_effected) }.each do |be|
value = value + be.value
end
However... the .map block returns some empty arrays. Not sure how to write it correctly.
Any help would be appreciated! Thanks
Probably along these lines, if what you want is the sum of values in the end:
value =
user.user_spells.flat_map do |us|
us.spell.buff_effects.where(stat_effected:'gold').map(&:value)
end.reduce(&:+)

Check if string contains element in Array

I'm using Rails and learning ActiveRecord and I came across a vexing problem. Here's an array in my model:
#sea_countries = ['Singapore','Malaysia','Indonesia', 'Vietnam', 'Philippines', 'Thailand']
And here's my ActiveRecord object:
#sea_funding = StartupFunding.joins(:startup)
.where('startups.locations LIKE ?', '%Singapore%')
What I'm trying to do is to return a result where a string in the 'locations' column matches any element in the Array. I'm able to match the strings to each element of an Array (as above), but I'm not sure how to iterate over the whole Array such that the element is included as long as there's one match.
The intent is that an element with multiple locations 'Singapore,Malaysia' would be included within #sea_funding as well.
Well, don't ask me why 'locations' is set as a string. It's just the way the previous developer did it.
You use an IN clause in your .where filter:
#sea_funding = StartupFunding.joins(:startup)
.where(["startups.locations IN (?)", #sea_countries])
#sea_countries.include?(startups.locations)
This will return a boolean TRUE if the value of the locations column in startups can be found in the sea_countries array, false if it is absent.
Could this work for you?
first = true
where_clause = nil
sea_countries.each do |country|
quoted_country = ActiveRecord::Base.connection.quote_string(country)
if first
where_clause = "startups.locations LIKE '%#{quoted_country}%' "
first = false
else
where_clause += "OR startups.locations LIKE '%#{quoted_country}%' "
end
end
#sea_funding = StartupFunding.joins(:startup)
.where(where_clause)

save information from another table

Hi everyone at this time i have two tables:
clientesultimasgestiones
clientesgestiones
And I want to put the whole information from clientesgestiones to clientesultimasgestiones but I want to save it field by field, at this momento I have this
cnx = ActiveRecord::Base.connection
cnx.execute("truncate table clientesultimasgestiones")
#informacion = Clientesgestion.all
#informacion.each do |f|
#clientesultimasgestion = Clientesultimasgestion.new
#clientesultimasgestion.save(f)
Here will be the code to save field by field from clientesgestiones table to the another one
end
Thanks for your help
EDIT: Finally i did it this way:
cnx.execute("truncate table clientesultimasgestiones")
#informacion = Clientesgestion.all
#informacion.each do |f|
l = Clientesultimasgestion.new
l.persona_id = f.persona_id
l.fecha_gestion = f.fecha_gestion
l.clientestipologia_id = f.clientestipologia_id
l.observacion = f.observacion
l.user_id = f.user_id
l.fecha_acuerdo = f.fecha_acuerdo
l.valor_apagar = f.valor_apagar
l.clientestipologiaanterior_id = f.clientestipologiaanterior_id
l.clientesobligacion_id = f.clientesobligacion_id
l.save
end
Thanks a lot :)
I would replace:
#clientesultimasgestion.save(f)
with:
#clientesultimasgestion.update_attibutes(f.attributes)
Also, seems what you want is to copy a table, see https://stackoverflow.com/a/13237661/1197775.
I think this question will help you to get lists of attributes and values.
After this, you need to set dynamically fields, for this purpose you can use method send. Something like this:
#clientesultimasgestion.send("#{field_name}=",field_value)

Store sql.eachRow() of groovy sql to a List

do you know how to store the result from
sql.eachRow()
of groovy sql to a list? for example def personList = [] ?
example:
sql.eachRow('select lastname from users where id='active')
What I want is to store the result ie. lastnames to a list ie def personlist = [];
I know I can easily do this by namedQuery and I've already done it. But their is some underlying reason about this. Thanks in advance.
def reqdColName = "lastname"
def query = "select $reqdColName from users where id='active'"
Straight option would be to use the rows() method.
def list= Sql.rows(query) //returns groovyrowresult as list
Another option is you could use the executeQuery instead, to get hold of the resultset of the query and thereby get an array/list on it.
def array = Sql.executeQuery(query).getArray(reqdColName)
//If you need as a list
def personList = Arrays.asList(array)
I know that the question has been asked a long time ago, but still, I feel the answer may be of help for someone out there.
def personlist = []
sql = Sql.newInstance(url, username, password, driver)
query = "select $reqdColName from users where id='active'"
sql.eachRow(query)
{
row-> personlist << row.toString()
}
sql.close()
personlist.each{println it} // you can also return the list
def personList = sql.rows("select lastname from users where id='active'")*.lastname

Resources