How do I implement aasm in Rails 3 for what I want it to do?
I am a Rails n00b and have been advised that in order for me to keep track of the status of my user's accounts (i.e. paid, unpaid (and therefore disabled), free trial, etc.) I should use an 'AASM' gem.
So I found one that seems to be the most popular: https://github.com/rubyist/aasm But the instructions are pretty vague.
I have a Users model and a Plan model. User's model manages everything you might expect (username, password, first name, etc.). Plan model manages the subscription plan that users should be assigned to (with the restrictions).
So I am trying to figure out how to use the AASM g开发者_StackOverflow中文版em to do what I want to do, but no clue where to start.
Do I create a new model ? Then do I setup a relationship between my User model and the model for AASM ? How do I setup a relationship? As in, a user 'has_many' states ? That doesn't seem to make much sense to me.
Any guidance would be really appreciated.
Thanks.
Edit: If anyone else is confused by AASMs like myself, here is a nice explanation of their function in Rails by the fine folks at Envy Labs: http://blog.envylabs.com/2009/08/the-rails-state-machine/
Edit2: How does this look:
include AASM
aasm_column :current_state
aasm_state :paid
aasm_state :free_trial
aasm_state :disabled #this is for accounts that have exceed free trial and have not paid
#aasm_state :free_acct
aasm_event :pay do
transitions :to => :paid, :from => [:free_trial, :disabled]
transitions :to => :disabled, :from => [:free_trial, :paid]
end
given it thought and this is what came out:
you're right about not making the states in the Plan
, dunno what I was thinking. Either do it in the User
model, or make an Account
model, which belongs_to :user
. Then, in your account try these (it's all about logics, so if you want more states, just mak'em up):
aasm_initial_state :free
aasm_state :free
aasm_state :paid
aasm_state :disabled
aasm_event :pay do
transitions :to => :paid, :from => [:free, :disabled]
end
aasm_event :disable do
transitions :to => :disabled, :from => [:free,:paid]
end
So when you create a new user, build an account for it too. Don't worry about the initial state at account creation, it will automatically be set to "free" when an account is created. Or, if it sounds easier, in the User
model, as you suggested.
精彩评论