Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Dave Faliskie
Dave Faliskie
17,793 Points

Does State_Machine still work with rails 4?

I'm doing the creating user friendships in rails and I just started adding states with state_machine. I keep getting an error when I try to actually create the "friendship"

protected method around_validation called for #<StateMachine::Machine

and points to the model shown below, saying there is no method create.

def self.request(user1, user2)
    transaction do
      friendship1 = create(user: user1, friend: user2, state: 'pending')
      friendship2 = create(user: user2, friend: user1, state: 'requested')

      friendship1.send_request_email unless friendship1.new_record?
      friendship1
    end
  end

this is the controller with the create method.

def create
    if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
      @friend = User.where(profile_name: params[:user_friendship][:friend_id]).first
      @user_friendship = UserFriendship.request(current_user, @friend)
      respond_to do |format|
        if @user_friendship.new_record?
          format.html { flash[:error] = "There was a problem."; redirect_to profile_path(@friend) }
          format.json { render json: @user_friendship.to_json, status: :precondition_failed }
        else
          format.html { flash[:success] = "Friendship created."; redirect_to profile_path(@friend) }
          format.json { render json: @user_friendship.to_json }
        end
      end
    else
      flash[:error] = "Friend required"
      redirect_to root_path
    end
  end

I believe I am doing everything correctly, unless there is something with state_machine I need to configure.

Does state_machine work with rails 4? if not how should I go about doing states?

Any input would be awesome, Thanks

2 Answers

Instead of

gem "state_machine"

use the updated version

gem "state_machines"