Search code examples
ruby-on-railsruby-on-rails-3model-associations

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
  end

Solution

  • @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

    self.name_your_method_here(user_id)
      User.find(user_id).problems
    end
    

    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.