为什么 .each 方法在 url 路径中为不同的购买提供相同的 :purchase_id (:show action)?

Why .each method gives me same :purchase_id for different purchases in url path (:show action)?

我是学习阶段的新手。我正在使用 seller/buyers 创建简单的电子商务网站,我在 "voyage"!

期间学到了很多东西

现在我正在尝试用after_create方法制作简单的通知系统。

我的问题是:

为什么我的 localhost:3000/notifications 中的每个通知在每个 product_purchase_path(每次购买的购买显示操作)上总是得到相同的 :purchase_id?

我没有收到错误,但是 notification/index 页面上的每个 link 不同购买都与第一个相同!

views/notifications/index.html.erb

 <%= @notifications.count %>
 <% @notifications.each do |n| %>
 <%= link_to n.purchase_id, product_purchase_path(@product, @purchase) %>
 <%= n.user_id %>
 <%= n.product_id %>
 <%= n.created_at %>
 <% end %>

买家创建采购请求后,会向卖家发送通知。卖家打开通知索引,他会看到所有订单通知。但是他无法访问特定的 Purchase show 操作,因为通知控制器没有给出具体的:puchase_id。 总是一样purchase_id,和索引中第一次通知的purchase_id一样!

购买模式

  class Purchase < ActiveRecord::Base
  after_create :create_notification

  has_many :notifications
  belongs_to :product
  belongs_to :buyer, class_name: 'User', foreign_key: :buyer_id
  belongs_to :seller, class_name: 'User' , foreign_key: :seller_id

  private

    def create_notification
      @user = seller_id
      @product = Product.find_by(self.product_id)
      @notification = Notification.create(purchase_id: self.id, product_id: self.product_id, user_id: @user, read: false)
   end  
 end

通知模型

 class Notification < ActiveRecord::Base
   belongs_to :purchase
 end

通知控制器

 class NotificationsController < ApplicationController

   def index
     @purchase = Purchase.find_by(params[:id])
     @product = @purchase.product
     @notifications = current_user.notifications 
     @notifications.each do |notification| 
       notification.update_attribute(:read, true)
     end
   end  
 end

路线

 Rails.application.routes.draw do  

 get 'notifications' => 'notifications#index'

 resources :conversations do
   resources :messages
 end

 resources :products do
   member do
     put "like", to: "products#upvote"
   end
   resources :comments
   resources :purchases
   get '/purchases/:purchase_id/accept' => 'purchases#accept', as: 'accept'
 end

 root 'pages#homepage'

 get 'pages/about'

所有链接都相同,因为 product_purchase_path(@product, @purchase) 使用始终相同的 productpurchase

您将需要这样的东西:

<% @notifications.each do |notification| %>
  <%= link_to(
        notification.purchase_id, 
        product_purchase_path(notification.product_id, notification.purchase_id)) %>
  ...
<% end %>

您在索引方法中设置了@purchase,然后使用@purchase 将link 设置为购买。你应该使用 n.purchase 而不是像这样

<%= link_to n.purchase_id, product_purchase_path(n.product_id, n.purchase_id) %>