I want to know field name corresponding to table caption for a given model in Rails.
I am displaying captions using a query model.
query.columns.map{|q| q.caption}
=> ["Tracker", "Status", "Priority", "Subject", "Assignee", "Target version", "Due date", "% Done"]
Column has names corresponding to captions
query.columns.map{|q| q.name}
=> [:tracker, :status, :priority, :subject, :assigned_to, :fixed_version, :due_date, :done_ratio]
My model looks like
Issue.columns.map{|q| q.name}
=> ["id", "tracker_id", "project_id", "subject", "description", "due_date", "category_id", "status_id", "assigned_to_id", "priority_id", "fixed_version_id", "author_id", "created_on", "updated_on", "start_date", "done_ratio", "estimated_hours", "parent_id"]
I want to get field name(the db field name) corresponding to a caption from the above information.
Sample association in the model
belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
So for above association i want to know the foreign key.
for assigned_to i want 'assigned_to_id'
The reflections hash holds this kind of information:
Issue.reflections['assigned_to'].foreign_key
You can also get other information, such as the class (.active_record) or the type of association (.macro). Prior to rails 4.2, the keys of this hash are symbols and not strings.
The correct way for Rails 4.2 is:
Issue.reflections['assigned_to'].options[:foreign_key]
Note that "assigned_to" is a string according to API:
Returns a Hash of name of the reflection as the key and a
AssociationReflection as the value.
http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflections
I'm posting this here in case this helps anyone else. I was trying to get the foreign key from proxy_association inside of an association extension.
You can get the reflection by simply using proxy_associtation.reflection.
Then, using #Frederick Cheung's method above, you can get the foreign_key like so:
reflection = proxy_association.reflection
reflection.foreign_key
You can also get the class_name in the same way:
reflection = proxy_association.reflection
reflection.class_name
Related
I have an Activity_Part model with a field called activity_json. this field is a hash that has a key named "image". I want to query/select only the ID of all Activity_Part only with activity_json field with key "image"
ActivityPart < ApplicationRecord {
:id => :integer,
:owner_id => :integer,
:activity_type => :string,
:activity_json => :json,
I thought of doing something like this:
x = ActivityPart.all
x.pluck(activity_json: 'image')
but I don't know how to return just the Activity ID with all the images in the activty_json field
I'll assume that you're using postgres.
jsonb type has the ? operator which can be used like this: ActivityPart.where("activity_json ? 'image'") as per documentation.
If your column is of a json type then consider changing it to jsonb. You can alternatively cast it to jsonb in the query like so: ActivityPart.where("activity_json::jsonb ? 'image'") but be aware that this might negatively affect the performance of the query.
I have a column car_details with 2000 entries, each of which is a hash of info that looks like this:
{"capacity"=>"0",
"wheels"=>"6",
"weight"=>"3000",
"engine_type"=>"Diesel",
"horsepower"=>"350",
"fuel_capacity"=>"35",
"fuel_consumption"=>"30"}
Some cars have more details, some have less. I want to rename the "fuel_consumption" key to "mpg" on every car that has that key.
Well, a previous answer will generate 2000 requests, but you can use the REPLACE function instead. Both MySQL and PostgreSQL have that, so it will be like:
Car.update_all("car_details = REPLACE(car_details, 'fuel_consumption', 'mpg')")
Take a look at the update_all method for the conditions.
See also PostgreSQL string functions and MySQL string functions.
Answer posted by #Ivan Shamatov works very well and is particular important to have good performances on huge databases.
I tried it with a PostgreSQL database, on a jsonb column.
To let it works we have to pay same attention to data type casting.
For example on a User model like this:
User < ActiveRecord::Base {
:id => :integer,
:created_at => :datetime,
:updated_at => :datetime,
:email => :string,
:first_name => :string,
:last_name => :string,
:custom_data => :jsonb
}
My goal was to rename a key, inside custom_data jsonb field.
For example custom_data hash content from:
{
"foo" => "bar",
"date" => "1980-07-10"
}
to:
{
"new_foo" => "bar",
"date" => "1980-07-10"
}
For all users records present into my db.
We can execute this query:
old_key = 'foo'
new_key = 'new_foo'
User.update_all("custom_data = REPLACE(custom_data::text, '#{old_key}'::text, '#{new_key}'::text)::jsonb")
This will only replace the target key (old_key), inside our jsonb hash, without changing hash values or other hash keys.
Note ::text and ::jsonb type casting!
As far as I know, there is no easy way to update a serialized column in a data table en masse with raw SQL. The best way I can think of would be to do something like:
Car.find_each do |car|
mpg = car.car_details.delete("fuel_consumption")
car.car_details["mpg"] = mpg if mpg
car.save
end
This is assuming that you are using Active Record and your model is called "Car".
In my rails app, i am using a legacy database.
class Expression < ActiveRecord::Base
set_table_name "EXPRESSION"
set_primary_key "EXP_ID"
belongs_to :sub, :foreign_key => "EXP_SUB_FK"
end
To save an entry in the 'EXPRESSION' table, i am using the following code in my controller method:
#expression = Expression.create(
:EXP_ID => 7,
:EXP_SUB_FK => 99991886,
:EXP_STRENGTH => 'strong',
:EXP_ADDITIONAL_STRENGTH => 'intense',
:EXP_COMPONENT_ID => 43444
)
I have to manually set the EXP_ID each time i save an entry (i will get the id from another table), but the above code does not save the EXP_ID. All the other values are saved except for the EXP_ID.
If i comment out 'set_primary_key "EXP_ID"' in the Expression model, it works but i need to define EXP_ID as primary key.
Is there a way of allocating a value for a primary key when saving an entry to the dbase?
I would be grateful if anyone can provide me with some hint.
Set the EXP_ID in a before_save filter defined in the the Expression model.
UPDATE:
Added Sample:
before_save :set_exp_id
def set_exp_id
self.exp_id = 5555555
end
I'd like to update a massive set of document on an hourly basis.
Here's the
fairly simple Model:
class Article
include Mongoid::Document
field :article_nr, :type => Integer
field :vendor_nr, :type => Integer
field :description, :type => String
field :ean
field :stock
field :ordered
field :eta
so every hour i get a fresh stock list, where :stock,:ordered and :eta "might" have changed
and i need to update them all.
Edit:
the stocklist contains just
:article_nr, :stock, :ordered, :eta
wich i parse to a hash
In SQL i would have taken the route to foreign keying the article_nr to a "stock" table, dropping the whole stock table, and running a "collection.insert" or something alike
But that approach seems not to work with mongoid.
Any hints? i can't get my head around collection.update
and changing the foreign key on belongs_to and has_one seems not to work
(tried it, but then Article.first.stock was nil)
But there has to be a faster way than iterating over the stocklist array of hashes and doing
something like
Article.where( :article_nr => stocklist['article_nr']).update( stock: stocklist['stock'], eta: stocklist['eta'],orderd: stocklist['ordered'])
UPDATING
You can atomically update multiple documents in the database via a criteria using Criteria#update_all. This will perform an atomic $set on all the attributes passed to the method.
# Update all people with last name Oldman with new first name.
Person.where(last_name: "Oldman").update_all(
first_name: "Pappa Gary"
)
Now I can understood a bit more. You can try to do something like that, assuming that your article nr is uniq.
class Article
include Mongoid::Document
field :article_nr
field :name
key :article_nr
has_many :stocks
end
class Stock
include Mongoid::Document
field :article_id
field :eta
field :ordered
belongs_to :article
end
Then you when you create stock:
Stock.create(:article_id => "123", :eta => "200")
Then it will automaticly get assign to article with article_nr => "123"
So you can always call last stock.
my_article.stocks.last
If you want to more precise you add field :article_nr in Stock, and then :after_save make new_stock.article_id = new_stock.article_nr
This way you don't have to do any updates, just create new stocks and they always will be put to correct Article on insert and you be able to get latest one.
If you can extract just the stock information into a separate collection (perhaps with a has_one relationship in your Article), then you can use mongoimport with the --upsertFields option, using article_nr as your upsertField. See http://www.mongodb.org/display/DOCS/Import+Export+Tools.
I would like to know if it is possible to get the types (as known by AR - eg in the migration script and database) programmatically (I know the data exists in there somewhere).
For example, I can deal with all the attribute names:
ar.attribute_names.each { |name| puts name }
.attributes just returns a mapping of the names to their current values (eg no type info if the field isn't set).
Some places I have seen it with the type information:
in script/console, type the name of an AR entity:
>> Driver
=> Driver(id: integer, name: string, created_at: datetime, updated_at: datetime)
So clearly it knows the types. Also, there is .column_for_attribute, which takes an attr name and returns a column object - which has the type buried in the underlying database column object, but it doesn't appear to be a clean way to get it.
I would also be interested in if there is a way that is friendly for the new "ActiveModel" that is coming (rails3) and is decoupled from database specifics (but perhaps type info will not be part of it, I can't seem to find out if it is).
Thanks.
In Rails 3, for your model "Driver", you want Driver.columns_hash.
Driver.columns_hash["name"].type #returns :string
If you want to iterate through them, you'd do something like this:
Driver.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
which will output the following:
id => integer
name => string
created_at => datetime
updated_at => datetime
In Rails 5, you can do this independently of the Database. That's important if you use the new Attributes API to define (additional) attributes.
Getting all attributes from a model class:
pry> User.attribute_names
=> ["id",
"firstname",
"lastname",
"created_at",
"updated_at",
"email",...
Getting the type:
pry> User.type_for_attribute('email')
=> #<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x007ffbab107698
#limit=255,
#precision=nil,
#scale=nil>
That's sometimes more information than needed. There's a convenience function that maps all these types down to a core set (:integer, :string etc.)
> User.type_for_attribute('email').type
=> :string
You can also get all that data in one call with attribute_types which returns a 'name': type hash.
You can access the types of the columns by doing this:
#script/console
Driver.columns.each {|c| puts c.type}
If you want to get a list of all column types in a particular Model, you could do:
Driver.columns.map(&:type) #gets them all
Driver.columns.map(&:type).uniq #gets the unique ones
In rails 5 this will give you a list of all field names along with their data type:
Model_Name.attribute_names.each do |k| puts "#{k} = #{Model_Name.type_for_attribute(k).type}" end
Rails 5+ (works with virtual attributes as well):
Model.attribute_types['some_attribute'].type
This snippet will give you all the attributes of a model with the associated database data types in a hash. Just replace Post with your Active Record Model.
Post.attribute_names.map {|n| [n.to_sym,Post.type_for_attribute(n).type]}.to_h
Will return a hash like this.
=> {:id=>:integer, :title=>:string, :body=>:text, :created_at=>:datetime, :updated_at=>:datetime, :topic_id=>:integer, :user_id=>:integer}
Assuming Foobar is your Active Record model. You can also do:
attributes = Foobar.attribute_names.each_with_object({}) do |attribute_name, hash|
hash[attribute_name.to_sym] = Foobar.type_for_attribute(attribute_name).type
end
Works on Rails 4 too
In Rails 4 You would use Model.column_types.