How do I modify rails associations from the command line? - ruby-on-rails

I added a relationship a little while ago to users (user has many cars).
But my boss has told me I need to make a new model for companies which the
cars will belong to the company and the leases will reside with the company so
company leases to many uses.
I can't find the specific migration that added the user_id to cars,
so is there a way to say modify?
rails g migration user_id_to_company_id_on_cars

Sorry, the question is hard to understand. Why should you modify rails association from command line, I think it is just belongs_to or has_many in the model?
If you want to do a migration on a model, you can do for example:
rails g migration add_user_id_to_cars user_id:integer

Related

Has_many through - Rails 5

I’m a rails newbie here and have this issue.
I have 3 models: Group, User, Subject, between Group and Subject I have a has_many through relation called GroupSubjects it works fine, the next is GroupUsers with a has_many through relation and works fine too, as new at this (like 1 mint learning rails) I want to assign a subject, with another view, not the new or edit templates, and with this view, and make the relation between Groups and Subjects, I want to save the user_id, group_id, and due date, in the GroupSubjects table.
I really need help, this has been a problem for at least 3 days.
Thanks for your help

Create join table using migrations or models?

As a Ruby on Rails newbie, I'm going through the Rails Guides and tonight is Active Record Migrations.
After finishing the section on Join Tables (http://guides.rubyonrails.org/active_record_migrations.html#creating-a-join-table), I'm left with the impression that using create_join_table is preferred (and simpler) than creating the Join Table via rails generate model.
Is this a correct assumption? Are there nuances I should be aware of?
Using the example in the guides of categories and products:
A join table works transparently. You only work with the two existing models (Category and Product), and the join table exists only to enable the HABTM relationship between them, so you can call category.products, or product.categories, and things just work.
Generating a model, on the other hand, would only be necessary if you need to work with that association as a distinct thing in your application (e.g. if you need to do things with a Categorization directly).
Contrast the Rails Guides description of a has_and_belongs_to_many association (read more):
A has_and_belongs_to_many association creates a direct many-to-many
connection with another model, with no intervening model. For example,
if your application includes assemblies and parts, with each assembly
having many parts and each part appearing in many assemblies, you
could declare the models this way:
with that of a has_many :through association (read more):
A has_many :through association is often used
to set up a many-to-many connection with another model. This
association indicates that the declaring model can be matched with
zero or more instances of another model by proceeding through a third
model. For example, consider a medical practice where patients make
appointments to see physicians. The relevant association declarations
could look like this:
So, yes, you're correct that create_join_table would be simpler than creating a model for the association. You can also see this answer for another explanation of the difference between these approaches.
As the docs mention...
Migration method create_join_table creates a HABTM join table
--
When you create a has_and_belongs_to_many relationship, you only need a join table (no model).
has_and_belongs_to_many join tables are different from has_many :through as they don't have an id (primary_key); has_many :through are meant to represent an interim model, so each "record" should have a unique identifier.
Thus, your question about whether it's better to create a join table through rails g model is false. has_and_belongs_to_many has no binding model. If you were using has_many :through, you'd be able to use the rails g model no problem.

Rails 3 sorting through parent association

I have a fairly straightforward question in Rails 3 to which I can't seem to find the answer:
Let's say I have 2 models: Customer, Project.
A Customer has_many projects
Project belongs_to customer
Now I want to sort a list of projects by "customer name" using Active Record (doing it with a Ruby array is easy enough, but I imagine this will get problematic once the number of project records grows).
How do I go about doing this with ActiveRecord?
Project.joins(:customer).order('customers.name')

How can I extend this Ruby ActiveRecord model?

I'm creating this little show scheduler thing.
I have the table shows, with title:string and description:text. I want to add days and times to the show (each show can have multiple days, and each day has their OWN times). How might I go about doing this?
I was thinking of making a times table. With the columns (show_id, day, and time). Then when listing the show, you search for times that meet that show_id and sort by day.
Any ideas, suggestions, etc. welcomed.
You'd create the Show model with the following command:
script/generate model Show title:string description:text
Then you'd create the ShowTime model:
script/generate model ShowTime date:datetime time:datetime
Then, in your show.rb model file, you'd define a has_many relationship like this:
has_many :showtimes
And in your ShowTime model file, you'd define a belongs_to relationship like this:
belongs_to :show
Seems to me the simplest solution to this would be to use a single DateTime Object, since you can get the day and the time from a Time object.
script/generate model ShowTime time:datetime
script/generate model Show title:string description:text showtime:references
Then put in the belongs_to/ has many_associations that Jacob referred to. I think having a separate model for the showtime would be better and allow for more flexibility. You should also look into the strftime method on a Time object, to format the time to your liking.
I think your idea is very reasonable (especially for someone who has no experience with programming). If you're interested in "Rails way" of implementing this, I would recommend checking has_many relationship in the Rails guide. (And I do recommend this guide in general, as it helped me a lot with Rails)

Rails ActiveRecord Relationships

How do the relationships magically function when only the models are altered?
If I want a "has__and___belongs___to__many" relationship, what should I name the table (so Rails can use it) that contains the two foreign keys?
Short answer: You can't just tell the models that they're related; there have to be columns in the database for it too.
When you set up related models, Rails assumes you've followed a convention which allows it to find the things you wrote. Here's what happens:
You set up the tables.
Following conventions in Rails, you name the table in a particular, predictable way (a plural noun, e.g. people). In this table, when you have a relationship to another table, you have to create that column and name it in another predictable way (e.g. bank_account_id, if you're relating to the bank_accounts table).
You write a model class inheriting from ActiveRecord::Base
class Person < ActiveRecord::Base
When you instantiate one of these models, the ActiveRecord::Base constructor looks at the name of the class, converts it to lowercase and pluralizes it. Here, by reading Person, it yields people, the name of the table we created earlier. Now ActiveRecord knows where to get all the information about a person, and it can read the SQL output to figure out what the columns are.
You add relationships to the model: has_many, belongs_to or has_one.
When you type something like, has_many :bank_accounts, it assumes a few things:
The name of the model that you relate to is BankAccount (from camel-casing :bank_accounts).
The name of the column in the people table which refers to a bank account is bank_account_id (from singularizing :bank_accounts).
Since the relationship is has_many, ActiveRecord knows to give you methods like john.bank_accounts, using plural names for things.
Putting all of that together, ActiveRecord knows how to make SQL queries that will give you a person's bank accounts. It knows where to find everything, because you followed a naming convention that it understands when you created the table and its colums.
One of the neat things about Ruby is that you can run methods on a whole class, and those methods can add other methods to a class. That's exactly what has_many and friends are doing.
This works because you are following "Convention over Configuration".
If you state that a customer model has many orders then rails expects there to be a customer_id field on the orders table.
If you have followed these conventions then rails will use them and will be able to build the necessary SQL to find all the orders for a given customer.
If you look at the development.log file when you are developing your application you will be able to see the necessary SQL being built to select all orders for a given customer.
Rails does not create tables without you asking it to. The creation of tables is achieved by generating a migration which will create/alter tables for you. The fact that you create a customer model and then state within it that it has_many :orders will not create you an orders table. You will need to do that for yourself within a migration to create an orders table. Within that migration you will need to either add a customer_id column or use the belongs_to: customer statement to get the customer_id field added to the orders table.
The rails guide for this is pretty useful

Resources