【发布时间】:2017-12-19 01:21:46
【问题描述】:
我正在为用户创建一个方法,可以看到每个用户的 perfil 并关注,我使用 CoffeScript 处理一个按钮并构建一个 JSON 文件,其中包含要关注的friend_id 并通过 POST 请求发送到 UsersController,之后即,通过参数发送到用户模型以在数据库中创建一行。
app.js.coffe:
$ = jQuery
$(document).on "ready page:load", ->
$('#follow_btn').on "click", ->
friend = $(this).data("friend")
boton = $(this)
$.ajax "/usuario/follow",
type: "POST"
dataType: "JSON"
data: {usuario: { friend_id: friend }}
success: (data)->
console.log data
boton.slideUp()
alert friend
error: (err)->
console.log err
alert "No hemos podido crear la amistad"
用户控制器
class UsuarioController < ApplicationController
skip_before_action :verify_authenticity_token
def show
@usuario = Usuario.find(params[:id])
end
def follow
respond_to do |format|
if current_usuario.follow!(post_params)
format.json {head :no_content}
else
format.json {render json: "Se encontraron errores"}
end
end
end
private
def post_params
params.require(:usuario).permit(:friend_id)
end
end
我认为问题出在执行 current_usuario.follow!(post_params)
没有发送friend_id
def follow!(amigo_id)
friendships.create(friend_id = amigo_id)
end
该行已创建,但字段friend_id 为Nil
我尝试像这样直接传递friend_id:
current_usuario.follow!(3)
这样字段friend_id就正确保存了
模型用户。
class Usuario < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable, omniauth_providers: [:facebook, :twitter]
has_many :posts
has_many :friendships
has_many :follows, through: :friendships, source: :friend
has_many :followers_friendships, class_name: "Friendship",
foreign_key: "friend_id"
has_many :followers, through: :followers_friendships, source:
:usuario
def follow!(amigo_id)
friendships.create!(friend_id: amigo_id)
end
def can_follow?(amigo_id)
not amigo_id == self.id or friendships.where(friend_id:
amigo_id).size > 0
end
def email_required?
false
end
validates :username, presence: true, uniqueness: true,
length: {in:5..20, too_short: "Al menos 5 caracteres", too_long:
"Maximo 20 caracteres"}
def self.find_or_create_by_omniauth(auth)
usuario = self.find_or_create_by(provider: auth[:provider], uid:
auth[:uid]) do |user|
user.nombre = auth[:name]
user.apellido = auth[:last_name]
user.username = auth[:username]
user.email = auth[:email]
user.uid = auth[:uid]
user.provider = auth[:provider]
user.password = Devise.friendly_token[0,20]
end
end
end
【问题讨论】:
-
您确定friend_id 正在进入
friend = $(this).data("friend")吗?
标签: ruby-on-rails json ruby coffeescript