w3d4
class TumblrPost < ActiveRecord::Base
validates presence: true
belongs_to(
:author,
class_name: “User”,
foreign_key: :author_id
primary_key: :id
)
end
class User < ActiveRecord::Base
validates presence: true, uniqueness: true
has_many(
:posts,
class_name: “TumblrPost”,
foreign_key: :author_id,
primary_key: :id
)
end
Today was all about associations. We also did some associations, and to end the day we finished up with a little bit of association creating. All in all, I’d say we’re getting pretty good at associations!
Rails continues to be magic, but we are slowly learning how the Wizard works. Sometimes however, there are things that just make you scratch your head. Today we spent about 20 minutes trying to do something the “long way” by making associations, when we could have just chained a few methods together. We figured it would be good practice to do so. We ended up creating a ‘has_many :through’ association that went through another ‘has_many :through’ association. Well apparently, that’s when Rails stops doing things magically because we were unable to get the method to work properly. After calling the TA over, we found out that for some reason, when you chain two ‘has_many :through’ associations together, the association won’t work properly unless the record you are using is already saved in the database. So, even though we had methods that worked perfectly fine when used separately, they broke when we tried chaining them together. I’m sure those are the kind of things you learn over time, and might be able to make sense of at some point, but for now it just seems a little odd.
It’s a good thing that we spent the last couple of days getting well acquainted with ActiveRecord, because tomorrow’s task is to build our own version of it, solo!