Brian Ngeywo
Brian Ngeywo

Reputation: 437

acts_as_state_machine helper method rails 6

i have a verified and unverified states in my booking model, how do i implement helper methods for my views? i would like something like this in my index views.

  <% @bookings.each do |booking| %>
    <%= link_to booking_path(booking) do %>
        <%= booking.name %>
        <% if verified_booking %>/* here is where i want implemented*/
            <div class="pt-4 font-semibold"><i class="fa fa-user-check"></i></div>
        <% end %     
    <% end %>
    </div>
  <% end %>

helper method

  def verified_booking
    !!Booking.verified
  end

booking model

  include AASM
  aasm :column => :state, :whiny_transitions => false do
    state :unverified, initial: true
    state :verified
    event :verify do
      transitions from: [:unverified], to: :verified
    end
  end

Upvotes: -1

Views: 89

Answers (2)

rmlockerd
rmlockerd

Reputation: 4136

EDIT Removed the sample AASM definition since you added yours to your question.

AASM will define public instance methods for each state you define, which you can use to check your state. So, in your case there will be .verified? and .unverified? methods on your instances. You can use these methods directly in the view, so you don't really need a helper method:

<% @bookings.each do |booking| %>
  <%= link_to booking_path(booking) do %>
    <%= booking.name %>
    <% if booking.verified? %>
      <div class="pt-4 font-semibold"><i class="fa fa-user-check"></i></div>
    <% end %>     
  <% end %>
  </div>
<% end %>

However, if you want to understand why the helper method in your question doesn't work, the helper method you give in your question won't work for two reasons. You call Booking.verified but Booking is the class and the AASM methods are instance methods (that is, they only work when invoked on an instance of Booking. You need to pass the individual booking instance to it from the view as a parameter (as @gordon has in their answer). The second issue is the method is .verified? (the question mark is part of the method name). So:

def verified_booking(booking)
  booking.verified?
end

Upvotes: 1

gordonturibamwe
gordonturibamwe

Reputation: 1087

ApplicationHelper.rb

def verified_booking(state)
 # check state in the database if it is verified
 # return true if state is verified
 # return false if not verified
end

html.erb

<% @bookings.each do |booking| %>
    <%= link_to booking_path(booking) do %>
        <%= booking.name %>
        <% if verified_booking(booking.state) %>/* here is where i want implemented*/
            <div class="pt-4 font-semibold"><i class="fa fa-user-check"></i></div>
        <% end %     
    <% end %>
    </div>
  <% end %>

Upvotes: 0

Related Questions