A Post belongs_to a User, and a User has_many Posts.
A Post also belongs_to a Topic, and a Topic has_many Posts.
class User < ActiveRecord::Base
has_many :posts
end
class Topic < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :topic
end
Well, that's pretty simple and very easy to set up, but when I display a Topic, I not only want all of the Posts for that Topic, but also the user_name and the user_photo of the User that made that Post. However, those attributes are stored in the User model and not tied to the Topic. So how would I go about setting that up?
Maybe it can already be called since the Post model has two foreign keys, one for the User and one for the Topic?
Or, maybe this is some sort of "one-way" has_many through assiociation. Like the Post would be the join model, and a Topic would has_many :users, :through => :posts. But the reverse of this is not true. Like a User does NOT has_many :topics.
So would this even need to be has_many :though association? I guess I'm just a little confused on what the controller would look like to call both the Post and the User of that Post for a give Topic.
Edit: Seriously, thank you to all that weighed in. I chose tal's answer because I used his code for my controller; however, I could have just as easily chosen either j.'s or tim's instead. Thank you both as well. This was so damn simple to implement. I think today might mark the beginning of my love affair with rails.
you can get the user_name and user_photo when displaying a topic and its posts...
something like:
#topic.posts.each do |post|
user_name = post.user.name
user_photo = post.user.photo
end
it's simple. sorry if i didn't understand your question very well.
Well, if what you want is display the user name of the author of a post, for example, you can do something like (not tested, but should work) :
#posts = topic.posts.all(:include => :user)
it should generate one request for all posts, and one for users, and the posts collection should have users.
in a view (haml here) :
- #posts.each do |post|
= post.user.name
= post.body
If I understand your question correctly, no, a has_many :through association is not required here.
If you wanted to display a list of all users that posted in a topic (skipping the post information), then it would be helpful.
You'll want to eager load the users from posts, though, to prevent n+1 queries.
Related
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 ...
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)
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)
Assuming I have these 4 models.
Then I'm using the gem called acts_as_paranoid for each model to implement logical deletion.
User
Community
Topic
Comment
User can resign anytime he wants. It means User's record will be deleted.
In general situation, communities, topics, and comments that are created by the user, should be also deleted together. (w/ dependant => destroy )
However, I don't want that. Because the other User might have added the community to his bookmark list. So for this reason they shouldn't be deleted.
When supposing that the user record was deleted but all those communities, topics and comments were remained, it starts returning nil error at the community page or wherever which was made by the user.
I'm coding like just this now.
It's gonna be nil everywhere since the user record is gone but all the records remain.
How can I handle this kind of problem?
views/communities/show.html.erb
<%= #community.user.username %>
What I want to do is, replacing the username displayed with this fixed word "Not Found User". Then possibly I'd just change the ownership(user_id) of community to the other User so that he can manage this community instead.
My association is just like this.
models/user.rb
has_many :communities
has_many :topics
has_many :comments
models/community.rb
belongs_to :user
has_many :topics
has_many :comments
models/topic.rb
belongs_to :user
belongs_to :community
has_many :comments
models/comment.rb
belongs_to :user
belongs_to :community
belongs_to :topic
I think the best way to handle this would be to refrain from deleting but put code in your display logic to handle a user that has been deleted. If you stick with acts_as_paranoid this would work fine, what I would do is use a helper method for username such as:
def community_username(community)
user = User.with_deleted.find(community.user_id)
if user.deleted_at.blank?
return user.username
end
"[deleted]"
end
You can put this in your appropriate helper or application helper and call it in your view like
<%= community_username(#community) %>
and it will display their username, or [deleted] if it has been deleted.
Note the above code is off the top of my head, you may need to adjust slightly if I'm forgetting acts_as_paranoids methods...
I have 3 models: Users, Articles and Comments.
Articel has many Comments.
Comments belongs to Article.
User has many comments.
Textbook case :)
I would like to make a list of Article IDs where the User has made Comments on. How do I do that?
I've tried variants of User.find(1).comments.articles_ids in the console but that gives me a undefined method error.
I'm sure it's simple, but I cant't figure it out :)
Thanks!
One way of doing it, that works with your current setup:
user.comments.collect(&:article_id).uniq
Alternatively I guess you could add a has_many :through to User:
class User < ActiveRecord::Base
has_many :articles, :through => :comments
end
then you can get the ids via user.articles.collect(&:id) (perhaps also user.article_ids, but I'm not sure about that).
I have a has_many :through association setup between two tables (Post and Category). The reason I'm using has_many :through instead of HABTM is that I want to do some validation on the join table (PostCategory).
So I have 4 models in use here:
User:
has_many :posts
has_many :categories
Post:
belongs_to :user
has_many :post_categories
has_many :categories, :through => :post_categories
Category:
belongs_to :user
has_many :post_categories
has_many :posts, :through => :post_categories
PostCategory:
belongs_to :post
belongs_to :category
Basically what I want is: Users can create posts, users can also create their own categories. A user can then categorize posts (not just their posts, any posts). A post can be categorized by many different users (in different ways potentially), and a category could contain many different posts (A user could categorize N posts under a specific category of theirs).
Here's where it gets a little bit tricky for me (I'm a Rails noob).
A post can ONLY belong to ONE category for a given user. That is, a post CANNOT belong to more than ONE category for any user.
What I want to be able to do is create a validation for this. I haven't been able to figure out how.
I've tried things like (inside PostCategory)
validates_uniqueness_of :post_id, :scope => :category_id
But I realize this isn't correct. This would just make sure that a post belongs to 1 category, which means that after one user categorizes the post, no other user could.
Really what I'm looking for is how to validate this in my PostCategory model (or anywhere else for that matter). I'm also not against changing my db schema if that would make things easier (I just felt that this schema was pretty straight forward).
Any ideas?
The simpliest way is to add user_id to PostCategory and to validate uniqueness of post_id with user_id scope.
Another way is to create custom validation which checks using sql if category owner has added category to that post.
Option 1 : use a before_save. In it, do a SQL look up to make sure a post with a similar category for your user doesn't exist (take care that on edit, you'll have to make sure you don't look-up for the current Post that is already in the DB)
Option 2 : custom validators :
http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#custom-validators
Never used them, but sounds like it can do what you want
I'm about to add a +1/likes feature to a personal project I'm working on. I'd like to know what the database design for this might look. I don't want to have several like tables but one like table to deal with all likes through out the website. I'd like to be able to "plug in" different parts of the site as they're created or at will.
E.G.
Microposts - users should be able to "like" microposts
Photos - users should be able to "like" photos
Let's say I create a games section and want users to be able to like games I want to be able to use the existing likes table instead of creating a likes table for games.
At the back of my mind I'm thinking the acts_as_tree plugin will be quite useful but could keeping things in the one likes table get messy after a while?
How can I add the likes feature to my app in the most sensible scalable way?
Take a look at polymorphic associations.
The example in the link provided talks about comments, but I think you want the same thing, with likes.
class Like < ActiveRecord::Base
belongs_to :likable, polymorphic: true
end
class Micropost < ActiveRecord::Base
has_many :likes, as: :likable
end
class Post < ActiveRecord::Base
has_many :likes, as: :likable
end
Here, both your Post and Micropost classes can have likes. And you can add some to any classes you want.
You can even do Like.all and, for each like, get the related object (a Post or a Micropost) with like.likable.
you should have a "Like" model or something, with, at least, this associations:
belongs_to :user
belongs_to :liked_object, :polymorphic => true
now you can do
Like.create :liked_object => micropost, :user => current_user
and in a future
Like.create :liked_object => game, :user => current_user
search for polymorphic associations (you may need a liked_object_type and liked_object_id on your migrations)