Associating users and articles - ruby-on-rails

So I just started with Rails and right now looking over HABTM. I am reading the DHH book and I see that he has two models namely article and user. They have HABTM relationships. I am wondering however whether I need to create a separate migration for the articles_users model by myself or will Rails do it for me?
If so, what happen if I create a new user and associate it with an article? Will Rails know right away what to enter inside the articles_users table?
Ex:
u = User.new(:name => "John");
a = Article.new(:title =>"Rails");
#can I do this?
a.user << u
#will rails automatically create an entry inside articles_users table?
I am somewhat confused on where Rails stop in terms of making tables for us or whatnot.

You will need to manually create the table with a migration. However, most rails developers now prefer Has Many Through instead of HABTM. Another benefit is that when you generate the "join model" rails will make a migration for you!

Related

Ruby on Rails adding relationship doesn't update new form

Basic rails question.
I have a class, let's say User, and another class, Category.
I set up a relationship between them, so that Users have categories and categories have users. When I go to users/new to create a new user though, there is no prompt for category. I'm expecting the rails magic to kick in and have done that, so I'm wondering if my expectations were wrong or if I haven't executed something properly.
You should set your User model to belong_to :category, and the Category to have_many :users.
That way, when you want to create a new user, it will ask you what category the user belongs to. You will probably need to run a migration to add the category_id index to the users table though. That will solve your problem.

How do I associate two entries in a database that are connected through a many-to-many relationship in Rails?

How do I associate two entries in a database that are connected through a many-to-many relationship in Rails?
I'm trying to associate Users and Issues for an issue tracker. I'm using has_and_belongs_to_many, not :through. I have a :user_id and :issue_id available to me, but there doesn't seem to be User.issues.find(id) or Issue.users.find(id) available to me. I have a route post "/", to: "home#create". I'm trying to make a create method in home_controller.rb.
From the look of it you're calling the method on the User class and not an instance.
If you want to get the issues connected to a user you need to fetch the user first:
User.find(id).issues
If you want to add a record to the association you can use the shovel method or any of the methods generated by the association macro:
User.find(id).issues << Issue.find(3)
User.find(id).issues.push(Issue.find(3))
User.find(id).issue_ids = [1, 2, 3]
Besides that you have a smattering of naming issues in your schema. Use snake_case everywhere in your database schema unless you have a good reason why you want to break the conventions and feel like explicitly configuring table and foreign key names.
I would also really question if you really want to use has_and_belongs_to_many. It should only really be used if you can't foresee that you ever will need to add additional attributes to the join table or never need to query the table directly - it seems pretty unrealistic that that would be true in an issue tracker. You want has_many through: - pretty much always.
I have a route post "/", to: "home#create". I'm trying to make a
create method in home_controller.rb.
Don't throw everything into a junk drawer controller. Think about your app in terms of resources that can be CRUD:ed and create controllers that handle just that resource. You should think about what the relation between a user and an issue is in your domain and how you can model it as an actual entity in the domain logic instead of just plumbing.
Maybe all I need to do is direct you to Rails Guides: Active Record Associations.
There is neither of these
User.issues.find(id)
Issue.users.find(id)
because when you are finding an issue or user by id, you don't use the association. Instead use these:
Issues.find(id)
Users.find(id)
Since the :id is unique this will work and should be what you want.
The only time you want to query issues or users using the association will be when you have the data for the other end of the relationship.
user = User.find(user_id)
issue = user.issues.where(id: issue_id)
Since the :id field is unique, this is the same as Issues.find(id). However if you want to get a collection of a user's issues with some other data, you can put the condition for that data in the where.
You can create an issue for a user this way:
user = User.find(user_id)
issue = User.issues.create( ... )

Cannot decide Model Associations in rails

I am new to rails and having a hard time figuring out what is the best association I can create for my models. The models I have are:
User
Article
List
ArticleLink
ArticleMeta
etc..
Here, User can create many Articles and Lists, an Article and List can belong to multiple Lists, an Article can have multiple ArticleLinks and ArticleMeta. I also want to delete all the references of a model wrt User when it is deleted. For example when an User deletes a List, all the reference of the List should be deleted from join tables.
Also please let me know what would be the most efficient way to insert records in each model and retrive records as well
Thank you for your help.
You can find all your answers over this link
http://guides.rubyonrails.org/command_line.html
As example
rails generate scaffold Articles name:string category:string lists:references
or
rails generate scaffold ArticleLinks name:string Article:references

Rails Cookies to manipulate database entries

I am trying to create a Rails app and I have a database consisting of author and a quotation by that author.
Now different users can choose to destroy or kill quotations from the database however it must only be deleted for that particular user i.e other users should still be able to see quotes that they didn't delete even if another user did.
I know that I would need to implement cookies but other than that I am unsure how to proceed. Can anyone point me to a tutorial or give me some pointers to get started on this complex task?
You surely have a User model in your application - one 'Rails-like' way to go about this would be to add a has_and_belongs_to_many relationship between User and Quotation.
This creates a relationship between each individual user and 'their' quotations. This relationship can be deleted without actually deleting a quotation, so all quotations would still be available to other users. If you want each user to be able to see all quotations by default, you would need to set up the relationship in advance.
Assuming you are using Devise to log your users in, all you'd need to do then is to replace Quotation.all with current_user.quotations in whichever controller you are using to display quotations.
The Rails guide linked above is quite helpful but basically you just need to add something like the following:
class User
has_and_belongs_to_many :quotations
before_create :add_quotations
def add_quotations
self.quotations << Quotation.all
end
#etc...
end
class Quotation
has_and_belongs_to_many :users
#etc...
end
and then run a migration adding a new table called users_quotations with the columns user_id and quotation_id.
EDIT
As #Yule pointed out this wouldn't let users see any quotations that were created after they were, and it would be quite annoying to have to set up the join tables in advance, so a more efficient way would be to have an excluded_quotations join table instead. So users can see all quotations except the ones that they have excluded.

Is dynamically changing Schema in Rails possible?

I would like to create new tables, add/delete columns from within my app. Is this possible?
Yes, you can do whatever the application database user can do to the database with ActiveRecord::Base.connection.execute. For example:
ActiveRecord::Base.connection.execute('ALTER TABLE people ADD name VARCHAR(60);')
But, if you add a column to a table, the corresponding attribute for the column will not be available in the ActiveRecord class until you restart the application.
No. It is not possible. Rails has to run migrations to get the tables in to the database. This requires that the server has be stopped and restarted after the migrations. You don't want this scenario in production.
Dynamic forms would accomplish what I believe you are after.
In short you make fields of a model a separate model. For instance
class Car
has_many :car_fields
end
class CarFields
belongs_to :car
end
Then you can make a form where the users can add and remove fields when the add a car to the database.
This is great explained by Ryan Bates here http://railscasts.com/episodes/403-dynamic-forms
I think you need a subscription to watch it. I you don't have one, get one. Railscasts is great!

Resources