When using model and migration generators in rails, you can use 'references' keyword as it was a data type to indicate that that field is a foreign key to another model, that is another table.
In this example I do so with an author field inside a book table (actually the field won't be exactly 'author').
rails g model book title publication_date:date author:references
Looking at the migrations and models created, we can better understand what are the information that rails has guessed from the command (ok this is not a part of the question but more a summary of the logic and the state of the art of this command):
Migration
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :title
t.references :author, index: true
t.date :publication_date
t.timestamps
end
end
end
Here rails uses again the 'references' method as it was a data type, but it actually means that we are a layer on top on the 'basic' data structure level, infact referencing an author means, at the data level, to add an 'author_id' and not an 'author' column . And it does right so (i've also checked on schema.rb to have confirmation).
In addition to this, it also puts an index: true that is a good practice from a performances point of view.
Model
Calling the generator in such a way also 'does something' on the model:
class Book < ActiveRecord::Base
belongs_to :author
end
that is, it adds the 'belongs_to :author'.
Notice that you can even create the book model and migration with the references clause to author before having author created. It enforces the consistence at the end (if it does at all, on such things).
Question
My question is on what rails doesn't do, that is: the has_many clause on the author model.
1) since normally it does exist before having created the book model, it should be easy for rails to add has_many to this. Is there any parameter to say rails to do so?
2) because of the fact that models can reference other models even if they are not yet created, another possibility would be declaring some kind of 'has_many' reference during author creation, is it possibile in some way?
There's no way of knowing where to put it, you'd have to specify it.
Such generators are designed to save time, and making such a thing saves too little or none. For instance, you'll have to specify explicitly the target class and whether it is has_one or has_many. That would subtract some of the usefulness of this, resulting in a very small positive or even a negative value.
I assume you mean that associations are available even on unsaved models. Yep, they are, but they're not too reliable. It works quite simple: an unsaved object has a collection for each association which stores temporary objects. When the main object is saved, new associated objects in these collections (not persisted yet) are created. An example:
a = Author.new(name: "Charles Dickens")
a.books << Book.new(title: "Oliver Twist")
a.save
That would save the new author to the database, and since his id would be known, it would then create a new book with that author_id. This behaves a little odd when it comes to has_many ... through: ... and possibly some other cases, so use this carefully.
Related
Before destroying a record, I'd like to check if there are any uses of it on other tables, even if the record itself has no knowledge of said uses.
For example, lets say I have a table of cost_centers, and I have a table of areas.
An area has a default cost_center. cost_centers have no connection with areas.
Which kind of validation can I use in order to prevent the user from destroying a cost_center, in order to keep an area consistent?
In other words, how can I search through the database to find out wether that record is a foreign key of some other record on any other tables?
When you designed your database, you've probably set all the references up.
In your migrations, it would look like this: t.references :cost_center.
If so, your Cost Center Model could have a has_one relationship to each table holding the reference which, in your example, would be has_one :area.
Then, to check if it is actually used, you could have a before_destroy callback to a method that checks if any has_one definition is not null:
class CostCenter < ActiveRecord::Base
has_one :area
before_destroy :check_usage
def check_usage
!self.area.nil?
end
end
I am running Ruby 2.1.9 and Rails 3.2.17.
First off, in Rails I always made the assumption that models should almost always be singular. I have seen model names like product_categories_product. This is fine and in habtm situation where you want a model to work with the relationship I have seen instructions_products. Which in Rails sorta may make sense, but I would rather name the model instruction_product. That was associated with a joins table named instructions_products.
In fact I was so frustrated I started looking at how rails names things and this happened? So clearly its an ok name for the model and would correspond to the correct table name. But what is more approriate?
ActiveModel::Naming.singular(InstructionsProducts)
returns instructions_products
Edited: The heart of the question is why is InstructionsProducts a valid model name in rails and why does my example above resolve to the singular 'instructions_products'. This seems odd considering the rails convention is to keep model names singular.
Your question is not completely clear to me.
By Rails conventions, model names are singular and written in camel case, for instance InstructionProduct. Each model matches a table in the database with the same words, down-cased, separated by '_' and in plural. instruction_products for the provided example.
Look at the following example using has_many:
class User < ActiveRecord::Base
has_many :contacts
end
class Contact < ActiveRecord::Base
belong_to :name
end
user = User.find(1)
user.contacts # returns an array of all the associated objects
When doing user.contacts, contacts is not the table name. It's the collection method, a placeholder for the symbol passed in the has_many method (please follow the has_many link and read what documentation says about has_many). Another name could be used, though:
class User < ActiveRecord::Base
has_many :personal_contacts, class_name: 'Contact' #, foreign_key: :contact_id
end
user = User.find(1)
user.personal_contacts
The class_name and foreign_key are required because rails conventions are not being followed. When using has_many :personal_contacts rails expects that personal_contacts will return an array of PersonalContact.
In Ruby you must start a class name with a capital word, so it is not possible to create a class named instruction_product. If you want to provide a name that does not follow the Rails convention, which I don't recommend, you will need to inform rails about the new table name:
Class AdminUser
self.table_name = "users"
end
Update 1:
As you already know, the convention states that the model should be declared as singular (class InstructionProduct instead class InstructionsProducts. However its just a convention. When a class inherits from ActiveRecord::Base, and a sql query is generated, ActiveRecord lowercases the class name, separates the words by _, converts to a plural name and uses it as the table name (mainly rails uses InstructionsProducts.model_name.plural which returns instructions_products).
You are assuming that singular actually does a name translation to singular, even if it's written in plural, but it doesn't. It assumes that you are using the convention, and mainly returns the class name underscored.
Looking at the rails source code (ActiveModel::Name), ActiveSupport::Inflector.underscore seems to be used (I just did a very superficial investigation, I have to admit). You can see how underscore works at documentation.
I have few question that bugs me off and need to be answered. Everything is related to the following tutorial Two Many-to-Many
Question 1
Does the join table using has_many need to have an id? or its best practice to remove the id? and add an index and using the two other primary key and set it unique and together?
Question 2
How can it be done in the migration of creating a table?
Question 3
After doing these relationship model and updating the data. I would like to create a new set of data everytime it is updated (to preserve the data). How would a controller would look in the update, new, create model?
Question 4
In the the middle table, I would like to set attributes such has a visible true, or false, how can I set also not just the third table but also the second table arguments
First ... a word of caution: That railscast is very old. There may be syntactical things in that episode that have been dated by new versions of rails.
Question 1
If you are using the has_many through method then you have to have an id column in the join model because you are using a full blown model. As Ryan mentions in the episode, you'll choose this method if you need to track additional information. If you use the has_and_belongs_to_many method, you will not have an id column in your table.
If you want to achieve a check where you do not allow duplicates in your many-to-many association (ie allow the pairing of item a with item b and again allowing another record of item a to item b), you can use a simple validates line with a scope:
validates_uniqueness_of :model_a_id, :scope => [:model_b_id]
Question 2
You can add indices in your migrations with this code
add_index :table_name, [ :join_a_id, :join_b_id ], :unique => true, :name => 'by_a_and_b'
This would be inserted into the change block below your create_table statement (but not in that create_table block). Check out this question for some more details: In a join table, what's the best workaround for Rails' absence of a composite key?
Question 3
I'm not completely clear on what you're looking to accomplish but if you want to take some action every time a new record is inserted into the join model I would use the after_create active record hook. That would look something like this.
class YourJoinModel < ActiveRecord::Base
after_create :do_something
def do_something
puts "hello world"
end
end
That function, do_something, will be called each time a new record is created.
Question 4
Using the has_many through method will give you access to the additional attributes that you defined in that model on both sides of the relationship. For example, if you have this setup:
class Factory < ActiveRecord::Base
has_many :widgets, :through => :showcases
end
class Widget < ActiveRecord::Base
has_many :factories, :through => :showcases
end
class Showcases < ActiveRecord::Base
belongs_to :factory
belongs_to :widget
attr_accessiable :factory_id, :widget_id, :visible
end
You could say something like
widget = Widget.first
shown = widget.showcases
shown.first.visible
or
shown = widget.showcases.where( :visible=> true )
You can also reach to the other association:
shown.first.factory
The reason for having an id column in an association is it gives you a way of deleting that specific association without concerning yourself with the relationship it has. Without that identifier, associations are hard to define outside of specifying all foreign keys.
For a trivial case where you have only two components to your key, this isn't that big a differentiator, but often you will have three or more as part of your unique constraint and there's where things get tricky.
Having an id also makes the relationship a first-class model. This can be useful when you're manipulating elements that have associated meta-data. It also means you can add meta-data effortlessly at a later date. This is what you mean by your "Question 4". Add those attributes to the join model.
Generally the join model is created like you would any other model. The primary key is the id and you create a series of secondary keys:
create_table :example_things |t|
t.integer :example_id
t.integer :thing_id
end
add_index :example_joins, [ :example_id, :thing_id ], :unique => true
add_index :example_joins, :thing_id
The main unique index serves to prevent duplication and allows lookups of key-pairs. The secondary serves as a way of extracting all example_id for a given thing_id.
The usual way to manipulate meta-data on the join model is to fetch those directly:
#example_things = #example.example_things.includes(:thing)
This loads both the ExampleThing and Thing models associated with an Example.
I'm having trouble with a model not honoring the :foreign_key policy.
Character model has the following fields:
name:string
level:int
realm:string
realm_id:integer
class Character < ActiveRecord::Base
belongs_to :realm
end
My Realms model looks like this:
class Realm < ActiveRecord::Base
has_many :characters, :foreign_key => "realm_id"
end
However, it seems like it's forcing the character model to use the :realm column as the foreign_key rather than :realm_id. I don't have any clue as to why or how to fix it. Is there any other way to make it ignore the :realm field and go for the :realm_id without having to change the name of the column?
[Edit for clarity]
The character model does have a realm_id:integer field. I have tried not having the foreign_key but the results with both is identical.
ruby-1.9.2-p136 :012 > c = Character.new
=> #
ruby-1.9.2-p136 :013 > c.realm = "Sargeras"
ActiveRecord::AssociationTypeMismatch: Realm(#2154038240) expected, got String(#2151988680)
Despite even having the foreign_key, it just refuses to let go of the realm column.
[Edit 2]
The realm column will just take over due to the has_many and belongs_to association. There is no way so far to break this, so the solution is to either remove the column (the approach i will take), or rename it to something different.
Did you make sure that your Character table has a realm_id column? Please make sure of that, and then get rid of foreign_key => 'realm_id, it is not necessary at all. Your program should work if you get both these things done.
You should not need the :foreign_key part here at all, since you're following the standard Rails naming convention, the realm_id column should be inferred from the model name.
EDIT
I see. I don't think you can have a column and an association by the same name in one model. The easiest solution would probably be to rename the "realm" column to "realmname" or something like that.
belongs_to :realm creates (among other things) methods called realm and realm= used as getters and setters. That means the method_missing magic that ActiveRecord uses to expose database columns as attributes is never triggered when you do Character#realm, as that method isn't in fact missing.
If you want to avoid renaming the realm column in your database, you could create attribute accessors for the field manually under another name:
class Character < ActiveRecord::Base
def realm_name
self['realm']
end
def realm_name=(value)
self['realm'] = value
end
end
This way you'll still have the realm column in your database and be able to access the attribute in Ruby, albeit under a different name. This isn't a great idea, though, as you'll be duplicating the realm name as both Character#realm_name and Character.realm.name.
I would ditch the realm column and instead make sure I use Realm objects when importing from the datasource:
character.realm = Realm.find_by_name('Sargeras')
That way you'd only realm data available where it makes sense; in the Realm model.
I was hoping I could get feedback on major changes to how a model works in an app that is in production already.
In my case I have a model Record, that has_many PhoneNumbers.
Currently it is a typical has_many belongs_to association with a record having many PhoneNumbers.
Of course, I now have a feature of adding temporary, user generated records and these records will have PhoneNumbers too.
I 'could' just add the user_record_id to the PhoneNumber model, but wouldn't it be better for this to be a polymorphic association?
And if so, if you change how a model associates, how in the heck would I update the production database without breaking everything? >.<
Anyway, just looking for best practices in a situation like this.
Thanks!
There's two approaches that might help you with this.
One is to introduce an intermediate model which handles collections of phone numbers. This way your Record and UserRecord can both belong_to this collection model and from there phone numbers and other contact information can be associated. You end up with a relationship that looks like this:
class Record < ActiveRecord::Base
belongs_to :address_book
delegate :phone_numbers, :to => :address_book
end
class UserRecord < ActiveRecord::Base
belongs_to :address_book
delegate :phone_numbers, :to => :address_book
end
class AddressBook < ActiveRecord::Base
has_many :phone_numbers
end
This kind of re-working can be done with a migration and a bit of SQL to populate the columns in the address_books table based on what is already present in records.
The alternative is to make UserRecord an STI derived type of Record so you don't need to deal with two different tables when defining the associations.
class Record < ActiveRecord::Base
has_many :phone_numbers
end
class UserRecord < Record
end
Normally all you need to do is introduce a 'type' string column into your schema and you can use STI. If UserRecord entries are supposed to expire after a certain time, it is easy to scope their removal using something like:
UserRecord.destroy_all([ 'created_at<=?', 7.days.ago ])
Using the STI approach you will have to be careful to scope your selects so that you are retrieving only permanent or temporary records depending on what you're intending to do. As UserRecord is derived from Record you will find they get loaded as well during default loads such as:
#records = Record.find(:all)
If this causes a problem, you can always use Record as an abstract base class and make a derived PermanentRecord class to fix this:
class PermanentRecord < Record
end
Update during your migration using something like:
add_column :records, :type, :string
execute "UPDATE records SET type='PermanentRecord'"
Then you can use PermanentRecord in place of Record for all your existing code and it should not retrieve UserRecord entries inadvertently.
Maintenance page is your answer.
Generate migration which updates table structure and updates existing data. If you're against data updates in migrations - use rake task.
Disable web access (create maintenance page)
Deploy new code
Run pending migrations
Update data
Enable web access (remove maintenance page).