我正在尝试做person所做的事情,但是使用rails 5。
在我的应用中,我有两个控制器和三个型号。
我的两个控制器是OrdersController
和ListingsController
。我的三个模型是Order
,Listing
和User
。
我正在尝试在我的OrdersController
中的销售和购买页面上创建与用户相关的链接,该链接指向我#show
中的ListingsController
操作。
我在销售和购买页面上的链接如下所示:
<% @orders.each do |order| %>
<tr>
<td class="center"><%= link_to 'View The Game Your Sold', listing_path(@listing) %></td>
</tr>
<% end %>
这是我的Order
型号:
belongs_to :listing
belongs_to :buyer, class_name: "User"
belongs_to :seller, class_name: "User"
这是我的OrdersController
:
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def sales
@orders = Order.all.where(seller: current_user).order("created_at DESC")
end
def purchases
@orders = Order.all.where(buyer: current_user).order("created_at DESC")
end
# GET /orders/new
def new
@order = Order.new
@listing = Listing.find(params[:listing_id])
end
end
这是我的Listing
型号:
belongs_to :user
has_many :orders
has_many :fullgames
def self.search(params)
listings = all # for not existing params args
listings = listings.where("name like ?", "%#{params[:name]}%") if params[:name]
listings
end
这是我的ListingsController
:
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, only: [:seller, :new, :create, :edit, :update, :destroy]
before_filter :check_user, only: [:edit, :update, :destroy]
def seller
@listings = Listing.where(user: current_user).order("created_at DESC")
end
# GET /listings
# GET /listings.json
def index
@listings = Listing.all.order("created_at DESC").search(params).paginate(:page => params[:page], :per_page => 2)
end
# GET /listings/1
# GET /listings/1.json
def show
end
end
这是我的User
型号:
has_many :listings, dependent: :destroy
has_many :sales, class_name: "Order", foreign_key: "seller_id"
has_many :purchases, class_name: "Order", foreign_key: "buyer_id"
答案 0 :(得分:0)
# Order Model
class Order < ApplicationRecord
scope :recent, -> { order("created_at DESC") }
end
# ListingsController
class ListingsController < ApplicationController
...
before_filter :authenticate_user!, only: [:show, :seller, :new, :create, :edit, :update, :destroy]
# GET /listings/1
# GET /listings/1.json
def show
@purchases = current_user.purchases.recent
@sales = current_user.sales.recent
end
end
# show.html.erb
# for purchases orders
<% @purchases.each do |purchase_order| %>
<tr>
<td class="center"><%= purchase_order %></td>
</tr>
<% end %>
# for sales orders
<% @sales.each do |sale_order| %>
<tr>
<td class="center"><%= sale_order %></td>
</tr>
<% end %>