在数据库中创建记录在rails中无法正常工作

时间:2016-12-07 12:34:31

标签: ruby-on-rails ruby activerecord

我正在创建两个用户之间友谊的实例。当我在rails控制台中创建它时,一切都按计划工作,但是,当我通过站点实际创建友谊时,状态列保持空白。如果有人能告诉我为什么会非常感激。

这是我的模型:

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

这是我的控制器

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

1 个答案:

答案 0 :(得分:1)

Friendship模型有attr_accessor :status,它会覆盖ActiveRecordstatus提供的默认getter setter方法。