Newbie needs help with e-commerce site

Hey there,

I’m super new to Ruby on Rails. Currently I’m currently working on an e-commerce project. (I’m building it for practice). My website has buyers and sellers. Each seller has their own page. How can set it up where you can see all the items listed by on seller on their page?

Here is my listings controller:

def shop @listings = Listing.where(seller: User.find(params[:id,])) @user = User.find(params[:id]) end

URL in my config/routes.rb

get ‘/shop/:id’ => ‘listings#shop’, as: ‘shop’

Hey there,

I'm super new to Ruby on Rails. Currently I'm currently working on an e-commerce project. (I'm building it for practice). My website has buyers and sellers. Each seller has their own page. How can set it up where you can see all the items listed by on seller on their page?

The key to this is your associations. If you have set up something like this:

class Seller   has_many :listings end

class Listing   belongs_to :seller end

Here is my listings controller:

  def shop   @listings = Listing.where(seller: User.find(params[:id,]))   @user = User.find(params[:id])    end

I'm not entirely clear who @user is meant to be here -- is this the seller? And you keep throwing around params[:id]. If this is the listings controller, :id should be the ID of a particular Listing, not a User. If you were using a UsersController#show method (or, to match my models above, a SellersController#show method, because you are "showing" a particular Seller), then you would have already loaded the @seller, and could simply call @seller.listings to get the collection in one step. After you have that working, then you could optimize it with an eager association:

@seller = Seller.find(params[:id]) @listings = @seller.listings

becomes

@seller = Seller.includes(:listings).find(params[:id]) @listings = @seller.listings

And that will save you the heartache of an N+1 query.

URL in my config/routes.rb

get '/shop/:id' => 'listings#shop', as: 'shop'

There's a great explanation of Rails' routing system, with particular emphasis on REST and Why It Is Good at Rails Routing from the Outside In — Ruby on Rails Guides

Also, if you haven't done so already (and your controller example hints to me that maybe you haven't) please give yourself a huge stepladder against the learning curve by visiting http://railstutorial.org and working all the way through the tutorial (it's free to use online). I had been using Rails professionally for nearly 3 years (and programming for many more years before that) when I did this, and I learned plenty. It will take you a few days, but you will save yourself literally years of wasted time in the future.

Walter