Rails: Getting all users from an associated model - ruby-on-rails

Say I have an article model, user model and comment model. If I want to get all users that commented on a particular article is this the best way or is there a better way?
User.find(Article.first.comments.pluck(:user_id))

You have a few options.
You can add
has_many :users, through: :comments
to Article then just say:
#article.users
If you don't want to do that for some reason you can do
#article.comments.collect(&:user)
I think this would be more efficient:
#article.comments.includes(:users).collect(&:user)
I hope that helps.

Related

This relationship doesn't allow for me to create posts through a user object

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)

Relationship advice/association logic in rails

I'm designing an application to create goals for a classroom - at the moment, the data relationships are modeled like this
I knew that out of inexperience I might run into problems and now I'm beginning to - specifically in my routes file - but also just for generally organizing the site and the data relationships.
When a user signs up, they add a student_group (or class), populate it with students and then add subjects. Later they add goals for each subject - although there should also be goals for a student_group, a student, or even the user. I was thinking of something like this - but would it be better as a has_many, through relationship?
Right now, I've only really done work on the User, Student_group, and Student models and these are fairly straight-forward. A user has many student_groups, and a student_group has many students. I'd like a second opinion before I proceed however, so that I don't have to end up going back and doing things over. Thanks!
I think you might be thinking too far ahead. Once you have your app built around your current data model, you'll know better whether you even want to expand it to include the concept of a goal that isn't part of a student's subject. If you decide that it is, then making goals belong_to a subject, student, or user will be pretty simple. At that point, you could also do something like
Class Student
has_many :personal_goals, class_name: "Goal"
has_many :goals, through: :subjects
def all_goals
goals + personal_goals
end
There's probably a more elegant way to model that last relationship. Would you need to go beyond that? Does it make sense to talk about a student group having a goal of its own? I don't know.
As I gone through your database design, I have found that you should have to use different type of relationships, that rails has provided us. I tried my best to design your schema as per my knowledge. you should define relationship in your model as I suggested below. Any good modification are highly appreciated.
User
has_many :student_groups
has_many :students, through: :student_groups
has_many :goals, as: :goalable
StudentGroup
belongs_to :user
has_many :students
has_many :goals, as: :goalable
Student
belongs_to :student_group
has_many :subjects
has_many :characteristics
has_many :goals, as: :goalable
Characteristic
belongs_to :student
Goal
belongs_to :goalable, polymorphic => true
I have defined some polymorphic associations in your schema. If you need any reference related to these association. visit http://guides.rubyonrails.org/association_basics.html
Hope it will help you. Thanks.

List of IDs from associated model

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).

Should this even be a has_many :through association?

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.

How to edit additional data in HABTM tables?

How do I update additional data in HABTM tables.
For Example: I have movies, people and HABTM movies_people tables, but there is additional persontype_id field in movies_people table which indicates role of this person in that particular movie. How do I add/change this value?
You should probably be using a has_many :through association, which was introduced just for this reason. Instead of just a movies_people table, you'd have an additional model, called somthing like Favorite or Viewing (depending on what you're trying to accomplish with the association), which belongs_to both :movies and :people, and in your Movie model, you'd do
has_many :favorites
has_many :people, :through => :favorites
This gives you access to movie.people for all the people who have favored this movie and movie.favorites to access anything that would be in your favorites table (like persontype_id)
Josh Susser's Article, Many-to-Many Dance Off does a much better job of explaining this that I could ever hope, so for additional help, I'd take a look at it. http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off
There is also a great Railscast on the subject, by Ryan Bates:
http://railscasts.com/episodes/47-two-many-to-many

Resources