aidiah aidiah - 6 months ago 21
Ruby Question

Separate post IDs

I have 3 controllers/models

routes.rb
:

resources :boards do
resources :posts do
resources :replies


Currently I have a separate column for the ID
:pid
and assign each post/reply with an incriminating PID.

In
models/reply.rb
:

class Post < ActiveRecord::Base
belongs_to :board
has_many :replies, dependent: :destroy
has_one :board
accepts_nested_attributes_for :replies
include FriendlyId
friendly_id :pid, use: :slugged
after_create :set_pid
def set_pid
post_max = Post.maximum(:pid)
reply_max = Reply.maximum(:pid)
if post_max.to_i < reply_max.to_i
self.update_attributes(:pid => reply_max.to_i + 1)
else
self.update_attributes(:pid => post_max.to_i + 1)
end
end
end


This works, but only if there is one board. How can I separate the PIDs per board?

Answer

You'll have to use a scope:

post_max = self.board.posts.maximum(:pid)
Comments