Search code examples
ruby-on-railsrubynotificationseachidentifier

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


I'm newbie in learning phase. I'm creating simple e-commerce site with seller/buyers, I learned so much during this "voyage"!

Now I am trying to make simple notification system with after_create method.

My question is:

Why am I keep getting same :purchase_id on every product_purchase_path (Purchase Show action for every purchase) for every notification in my localhost:3000/notifications?

I'm NOT getting errors, but every link to different purchase on notification/index page is same as first one!

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 %>

After the buyer creates Purchase request, notification is sent to seller. Seller opens notification index and he see all notifications for orders. But he can't access specific Purchase show action, because notification controller doesn't give specific :puchase_id. It is always the same purchase_id, same as purchase_id in first notification in index!

Purchase model

  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

Notification model

 class Notification < ActiveRecord::Base
   belongs_to :purchase
 end

Notification controller

 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

Routes

 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'

Solution

  • You're setting @purchase in your index method and then setting the link to the purchase using @purchase. You should use n.purchase instead like so

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