I'm creating a website where users can post their items & services for sale (a classified ads site) and have setup the 'listing', 'category', and 'user' models. The listings and categories are associated with each other in a "has_many"-->"belongs_to" relationship, with categories owning listings.
However, even though the Listings are successfully associating with a Category upon creation of a new listing (I believe...?), the "show" page for Categories is not displaying it's associated listings; (displaying the "No listings to display" message"). What could be the problem?
-Here's my 'show' page for Categories:
<h1><%= @category.name %></h1>
<%= render partial: 'listings/list', locals: {
listings: @category.listings } %>
-and here's the controller for Categories:
class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
end
end
-Here's the controller for Listings:
class ListingsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, except: [:create, :index, :new]
def index
@listings = Listing.all
end
def show
end
def new
@listing = Listing.new
end
def edit
end
def create
@listing = current_user.listings.build(listing_params)
if @listing.save
redirect_to @listing
flash[:success] = "Listing was successfully created."
else
render 'new'
end
end
def update
if @listing.update(listing_params)
flash[:success] = "Listing was successfully updated."
redirect_to @listing
else
render 'edit'
end
end
def destroy
@listing.destroy
flash[:success] = "Listing deleted."
redirect_to request.referrer || root_url
end
private
def listing_params
params.require(:listing).permit(:name, :description, :price, :image,
:category_id)
def correct_user
@listing = current_user.listings.find_by(id: params[:id])
redirect_to root_url if @listing.nil?
end
end
-This is listing partial referenced in the show page:
<% if @listings.nil? %>
No listings to display! Go <%= link_to 'create one', new_listing_path %>.
<% else %>
<table class="table table-striped">
<tbody>
<% @listings.each do |listing| %>
<tr>
<td><%= link_to listing.name, listing %></td>
<td class="text-right">
<% if listing.price %>
<%= number_to_currency(listing.price) %>
<% end %>
</td>
<td class="text-right">
<% @listings.each do |listing| %>
<% if listing.category %>
<%= link_to listing.category.name, listing.category %>
<% end %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
-The model file for listing:
class Listing < ActiveRecord::Base
belongs_to :user
belongs_to :category
default_scope -> { order('created_at DESC') }
validates :name, presence: true
validates :description, presence: true
validates :price, presence: true
validates :user_id, presence: true
mount_uploader :image, ImageUploader
end
-The model file for category:
class Category < ActiveRecord::Base
has_many :listings
end