Rails - Show all models that belongs_to this User

If I have a User that has_many :problems, assuming I have set up the necessary association between User and Problem , how can I do something like:

  # UsersController.rb
  def students_problems
     @userId = params[:user_id]
     @problems = give me all problems associated with this @userId


@user = User.find(params[:user_id])

@problems = @user.problems

Ideally you would want to do this in a model if you plan to do more with your code. So you can create a model method like this for your controller.

@problems = User.name_your_method_here(params[:user_id])

Then in your User model you have


And you might want to add some conditionals to make sure the user_id matches a real user but I'll leave that up to you to do.

EDIT: As lebreeze suggests, it might be wise to change the name of the method to something different, at least to what it relates with what you're doing with your code.

Assuming all your associations and db fields are correct.

@problems = User.find(params[:user_id]).problems

Need Your Help

NSURLs for all video from Photo Album

ios iphone objective-c

I am trying to make a custom app where I would like to display all of users videos from their photo album into a UITableView. The problem that I have is that I cannot figure out how can I get to al...

Writing a simple bash like command prompt, that supports auto completion (handles tab key)

linux perl command-prompt

I was trying to implement a simple shell prompt, that only needs to handle internal commands, I tried Term::ReadLine, but that one doesn't handle Tab key like bash does, so I'm wondering what else ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.