top | item 19851673

(no title)

localhostdotdev | 6 years ago

    rails g model Post published_at:datetime title content:text
    rails g model Comment post:references author published_at:datetime content:text
    rails g model Tag name
    rails g model PostTag post:references tag:references

    class Post < ApplicationRecord
      has_many :comments
      has_many :post_tags
      has_many :tags, through: :post_tags
    end

    class Tag < ApplicationRecord
      has_many :post_tags
      has_many :posts, through: :post_tags
    end
from there it's just regular rails:

    Tag.find_by(name: "something").posts
    Post.joins(:tags).where(tags: { name: "something" })
    Tag.create(name: "something")
    Post.create(...)
    Tag.first.posts << Post.all.sample(2)
made a little repo if people want to play with it: https://github.com/localhostdotdev/bug/tree/orm-or-not-orm

discuss

order

davidcuddeback|6 years ago

You forgot to add an index on tags.name and null constraints on the rest of the columns.

> from there it's just regular rails

That's the problem. Examples like this focus on the first few minutes of development. Not the subsequent years of maintenance.

vinceguidry|6 years ago

> Not the subsequent years of maintenance.

You're gonna have to pry the Rails from my cold dead fingers if you want me to maintain a web app's database abstraction layer long-term. No other tool works half as well as ActiveRecord. You could maybe convince me to try out https://rom-rb.org/ but only on a brand new project and only if Rails isn't appropriate.

If it's a project that wasn't built with Rails, I'm going to want https://github.com/jeremyevans/sequel if ActiveRecord is too much trouble to introduce.

djupblue|6 years ago

Adding an index on tags.name is likely not very useful on its own but adding an index with an uniqueness constraint to prevent duplicates is probably a good idea. Assuming there are just a few different tags records (<1000) then a sequential scan is generally either insignificantly slower or even faster than an index scan.

>Not the subsequent years of maintenance.

I'd much rather maintain this example than a code base replicating the same behavior without an ORM.

blueplanet200|6 years ago

Rails is also fine to maintain down the road. Certainly easier than any data layer most engineers would make by hand.