Question

I need help fixing this relationship in Rails 4.1,

User Model Relationship

has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs

Blog Model Relationship

has_many :posts

Post Model Relationship

belongs_to :blog
belongs_to :user

Issue?

The following, in rails c, works - how ever the user id is not passed in:

User.find_by_x(x).blogs.find_by_x(x).post.create(x)

The post is created for a user who has said blog attached, but because of how this type of chaining works, only the blog_id is passed to the post and not the user_id Its crucial I have both blog and user id.

So I thought, why not just create the post through the user object and pass in the blog id.

User.find_by_x(x).posts.create(x, blog_id: y) # Where y represents a blog the user is associated with.

Well that's all good and stuff accept I get this error:

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly: Cannot modify association 'User#posts' because it goes through more than one other association.

I believe the issue is the fact that I have a join table and I am saying has_many :posts, through: blogs Most people might assume that "just remove the through part." How ever I need this type of relationship where a user can have many blogs and blogs can belong to many users and posts belongs to a blog and to a user but a user can have many posts ....

So is there a way to fix this to keep my concept or ...

Was it helpful?

Solution 2

The correct solution to this issue is a couple of things, one I needed to make sure that the realtionship between blog and user was the same as user and blog so in the blogs model I added:

has_and_belongs_to_many :users, join_table: 'blogs_users'

Then I needed to create posts at a post level, not a user level. So instead of, @user.posts.create() I need to do Post.create(blog_id: x, user_id: x) and then @user.posts will work properly (assuming the user has 2 blogs with one post in each you'll get back both posts)

OTHER TIPS

the way you are creating posts does not make much sense.

this would be the usual way of doing it:

blog = current_user.blogs.find(params[:blog_id])
post = blog.posts.create(params[:post])

respond_with(post)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top