Rails App incremental ticket number for different accounts
I have a multi-tenant Rails app that creates support tickets. The tickets are supposed to have incremetal ticket numbers. I can't use the ID column, because since the app will be used 开发者_C百科by different accounts, they will find odd ticket numbers.
For example, if Account 1 creates two tickets, they get Ticket #1 and Ticket #2. Account 2 creates one ticket, he gets Ticket #3. (That would be odd because he's supposed to get Ticket #1, because it's the first ticket he creates under his account).
So, I'm supposed to add a ticket_number column to the tickets table. Now, how would you go about incrementing the numbers automatically and being separated from other accounts?
class Ticket
after_create :increment_tickets
def increment_ticket
Account.increment_counter(:ticket_number, self.account_id)
end
end
The solution should be that your customer table (you have to have one, for to be multi-tenant) should be expanded by the following migration:
class AddCounter < ActiveRecord:Migration
def self.up
add_column :accounts, :ticket_counter, :integer
add_column :tickets, :ticket_number, :integer
end
end
Every time, you create a ticket for the customer, you have to increment the ticket number. See the post of @fl00r. The creation of the Ticket should go like that (code from a controller of mine):
class TicketController
def create
#Here comes your addition:
params[:ticket][:ticket_number]= Account.find(session[:account_id]).ticket_counter
# Here comes the rest
@article = Ticket.new(params[:ticket])
...
end
end
The context here is:
- You have to know which is the current account (see
session[:account_id]
, if you have other stores for the current account, use that). - The ticket is created with the
ticket_counter
in theparams[:ticket]
hash. - After the creation, the counter in the account is incremented (see the answer of @fl00r).
精彩评论