Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Osgaldor Storm
1,119 PointsRails: db tables and related models
I am building a Rails app and I have a question that i need a little guidance on. How related are models? If I have a message object that belongs to an inbox object and the inbox object belongs_to the User object. Is it therefore true that the message object also belongs_to a User? it seems kind of convoluted, but also very logical.
2 Answers
Nick Fuller
9,027 PointsHi Osgaldor!
This in not convoluted at all, and in fact this is what makes Rails (and Ruby) so fun to use! Your logic is absolutely correct. There are a couple of ways to go about this, but I personally like to use the has_many through method. I will demonstrate below.
So, given we are setup like you have described above (if I'm following correctly!)
class Inbox < ActiveRecord::Base
belongs_to :user
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :inbox
end
Now setting up the User model so it can get a list of all messages is as simple as this
class User < ActiveRecord::Base
has_many :inboxes
has_many :messages, through: :inbox
end
Essentially what ActiveRecord is going to give us is ALL the messages no matter how many inboxes a user has. You can define more methods on your user model to customize the results. For example, given there is an inbox with a name attribute of 'Spam' and I wanted to call a method on a user instance to get a list of all the spam mail, I would write it like this:
class User < ActiveRecord::Base
has_many :inboxes
has_many :messages, through: :inbox
def spam
messages.where('inboxes.name = ?', 'Spam')
end
end
Now if I find a user I can get a list of their spam
class InboxesController < ApplicationController
def spam
@user = User.find(params[:user_id])
@spam_mail = @user.spam
end
end
I hope this helps!
Osgaldor Storm
1,119 PointsBrilliant! Thank you!