Search code examples
rubymodel-view-controllersinatracrud

Sinatra: Why are my artists saving to all users and not just the currently logged in user?


The artist objects save to @artists but no matter which user I log in as, i see the whole list

Models

class User < ActiveRecord::Base
    has_many :users_artists
    has_many :artists, through: :users_artists
    has_many :artworks, through: :artists
end

class Artist < ActiveRecord::Base
    has_many :artworks
    has_many :users_artists
    has_many :users, through: :users_artists
end

class UserArtists < ActiveRecord::Base 
    belongs_to :user
    belongs_to :artist
  end

Relevant code from my artists controller, and the paths seem to be functioning properly, the issue lies with the way artists are save

 get '/artists' do 
       if   !logged_in?
            redirect to '/login'
       else
            @artists = Artist.all
            erb :'artists/index'       
       end
    end

    get '/artists/new' do 
        if !logged_in?
            redirect '/login' 
        else
            @artist = Artist.new
            erb :'artists/new'
        end
    end

    post '/artists' do 
        if !logged_in?
              redirect to "/login"
            else
            @artist = current_user.artists.create(name: params[:name],notes: params[:notes])
            current_user.save  
                if
                  @artist.save
                  redirect "/artist/show"
                else 
                    redirect to "/artists/new"
                end
        end
    end

Migrations, i've changed the UsersArtists pluralization a few times and felt like i was getting closer.

class CreateArtists < ActiveRecord::Migration[6.0]
  def change
      create_table :artists do |t|
        t.string :name
        t.text :notes
        t.integer :user_id
        t.timestamps null: false
      end
    end  
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.text :email
      t.string :password_digest

      t.timestamps null: false
  end
  end
end

class CreateUsersArtists < ActiveRecord::Migration[6.0]
  def change
    create_table :users_artists do |t|
      t.integer :user_id
      t.integer :artist_id
      t.timestamps null: false
    end
  end
end

Solution

  • It's because of this:

    @artists = Artist.all
    

    This loads the full artist list, and that's what you're displaying.

    Instead, filter it by the current user:

    @artists = current_user.artists