Question

I have a rails 4.1 app with the following relationships:

  • users has_many blogs, blog belongs to user
  • user has_many posts through blogs
  • posts belongs_to blog
  • blog has_many posts

This type of relationship allows me to do something like:

@user = User.create(name: 'Sally') 
@blog = @user.blogs.create(title: 'New Blog')
@blog.posts.create(title: 'New Post', content: 'Hello World')

If you trace this back you will see that sally created a blog, titled new blog with one post called new post.

How ever lets say you invited George to the blog to be a guest author, so lets assume you have some kind method that adds users to a blog:

@user_george = User.create(name: 'George')
@blog.add_user(@user_george.id)

Great, so now George can post a blog:

@user_george.blogs.find_by_id(@blog.id).posts.create(title: 'Georges Post', content: 'Some content')

Now we can search for georges posts and sallies posts. How ever this is where I run into problems, what if you're only given the blog object returned as json. So far this blog has two users, two posts. The current way to find a post (at the model level) is directly through the user model:

User.find_by_id(x).posts.all()

There are a couple of issues with this that I have found. One George cannot be added to the blog because a particular blog belongs to a user (I assume user has many and belongs to blog through join table blogs_users would fix that?) Also How am I suppose to know who wrote what post for what blog assuming this was given to you as an API? So lets say sally wanted to use this to display both her post and George's guest post on her web site ...

Was it helpful?

Solution

1- George cannot be added to the blog because a particular blog belongs to a user

One way is to define two type of associations referencing the User model from the Blog , something like:

class Blog < ActiveRecord::Base
  has_one :owner, class_name: "user", foreign_key: :owner_id
  has_many :users
end

This way many users may belong to a blog while it has only one owner.

2- How am I suppose to know who wrote what post for what blog

Your current setup does support doing:

@user.posts.includes(:blog)
#should give you all posts for user George along with blog details for each post

3- How to build an Optimal design?? (my opinion)

I learned (the hard way) that making the optimal solution when it comes to design won't work by trying to make it perfect from the beginning !! Start experimenting with what you came up with and by making small changes, you will gradually reach your optimal solution.

What i want to say is, "Don't Over-Think It", because you will never figure what's wrong till you play with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top