我有使用state_machine gem编写的代码,但是如何使用assm gem编写等效的代码?
state_machine :state, initial: :pending do
after_transition on: :accept, do: :send_acceptance_email
state :requested
event :accept do
transition any => :accepted
end
end
接受友谊请求后怎么办
def self.request(user1, user2)
transaction do
friendship1 = create!(user: user1, friend: user2, state: 'pending')
friendship2 = create!(user: user1, friend: user2, state: 'requested')
friendship1.send_request_email
friendship1
end
end
def send_request_email
UserNotifier.friend_requested(id).deliver
end
def send_acceptance_email
UserNotifier.friend_accepted(id).deliver
end
User.rb
has_many :friends, through: :user_friendships,
conditions: { user_friendships: { state: 'accepted' } }
has_many :pending_user_friendships, class_name: 'UserFriendship',
foreign_key: :user_id,
conditions: { state: 'pending' }
has_many :pending_friends, through: :pending_user_friendships, source: :friend
您需要在模型中包括这条线
include AASM
#尽管我一直将状态用作状态机的列,但是您也可以尝试将状态用作所使用的列。希望这不会成为问题。
aasm column: 'state', initial: :pending, whiny_transitions: true do
state :requested # im not seeing any event which set this state
state :accepted
#if you want an to trigger request event from any state simply add this
event :request, after: Proc.new { send_request_email } do transitions to: :requested end
#if you want to trigger accepted state from any state do this
event :accept, after: Proc.new { send_acceptance_email } do transitions to: :accepted end
#if you want to trigger accepted state from only requeste state
event :accept, after: Proc.new { send_acceptance_email } do transitions from: :requested, to: :accepted end
end
如果您不喜欢异常,而希望使用简单的true或false作为响应,请告诉AASM不要抱怨:
:whiny_transitions => false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句