我正在创建两个用户之间友谊的实例。当我在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
答案 0 :(得分:1)
Friendship
模型有attr_accessor :status
,它会覆盖ActiveRecord
列status
提供的默认getter setter方法。