Search code examples
ruby-on-railsruby-on-rails-3.1

When creating a new object how do I relate it to current user


I have a model in which allows a user to create many of. I want only the user to see these objects if they are logged in. So as of now I have the object belongs_to:user and user has_many:objects set, but how do I set the user property when an object is created. I basically want the user to create this and then later on display all of them back using object find(where user=current_user).


Solution

  • In your objects_controller.rb create action do this:

    @object = current_user.objects.build(params[:object])
    

    Instead of:

    @object = Object.new(params[:object])
    

    To retrieve the current user's objects, simply:

    @objects = current_user.objects