我正在创建一个用户可以发布他们的商品和网站的网站。销售服务(分类广告网站)并设置了“列表”,“类别”和“用户”模型。列表和类别以“has_many” - >“belongs_to”关系相互关联,其中类别拥有列表。
然而,即使列表在创建新列表时成功与类别关联(我相信......?),类别的“显示”页面也不会显示它的相关列表; (显示“无要显示的列表”消息“)。可能是什么问题?
- 这是我的“显示”页面类别:
<h1><%= @category.name %></h1>
<%= render partial: 'listings/list', locals: {
listings: @category.listings } %>
- 这是类别的控制器:
class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
end
end
- 这是清单的控制器:
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
- 这是在展示页面中列出的部分参考:
<% 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 %>
- 列出的模型文件:
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
- 类别的模型文件:
class Category < ActiveRecord::Base
has_many :listings
end
答案 0 :(得分:3)
<%= render partial: 'listings/list', locals: {
listings: @category.listings } %>
通过listings
var而不是@listings
制作列表,与您的模板一样。
只需删除@符号。