0

I am creating an instance of a friendship between two users. When I create it in the rails console everything works as planned, however, when I actually create the friendship through the site the status column is left blank. If anyone can tell me why it would be really appreciated.

here is the model I have:

class Friendship < ApplicationRecord

  attr_accessor :status, :accepted_at

  belongs_to :user
  belongs_to :friend, :class_name => "User"

  def self.request(user,friend)
    unless user == friend or Friendship.exists?(user: user, friend: friend)
      transaction do
        create(:user => user, :friend => friend, :status => 'pending')
        create(:user => friend, :friend => user, :status => 'requested')
      end
    end
  end

  def self.accept(user,friend)
    transaction do
      accepted_at = Time.now
      accept_one_side(user,friend,accepted_at)
      accept_one_side(friend,user,accepted_at)
    end
  end

  def self.accept_one_side(user,friend,accepted_at)
    request = Friendship.where("user_id = #{user.id} AND friend_id = #{friend.id}")
    request.update_all(:status => 'accepted', :accepted_at => accepted_at)
  end
end

and this is my controller

class FriendshipsController < ApplicationController
  def create
    friend = User.where(email: params[:friend_email]).first
    Friendship.request(current_user,friend)
    redirect_to user_profile_path(current_user)
  end

  def friendship_params
    params.require(:friendship).permit(:friend_email)
  end
end
4
  • Friendship model has attr_accessor :status - status looks like a virtual attribute. Do you have a column called status ? Commented Dec 7, 2016 at 12:38
  • Yeah i have a status column, but it is only set to pending/requested when i create the friendship from the command line. Is that to do with the attr_accessor then? Commented Dec 7, 2016 at 12:40
  • 2
    Yes, why do you have attr_accessor :status ? When you have a column named as status, ActiveRecord already creates getter setter methods for it. Commented Dec 7, 2016 at 12:42
  • Thanks alot that solved it. So when i added the accessor did that overwrite the methods that active_record had created? Commented Dec 7, 2016 at 12:44

1 Answer 1

1

Friendship model has attr_accessor :status, which overrides the default getter setter methods provided by ActiveRecord for your status column.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.