Rails 5.1:向模型发送参数的问题

Rails 5.1: issue to sending parameter to a model

我正在制作一种方法,让用户可以看到每个用户的个人资料并关注,我使用 CoffeScript 来处理一个按钮并构建一个 JSON 文件,其中包含要关注的 friend_id 和向 UsersController 发送 POST 请求,然后通过参数向 Users 模型发送以在数据库中创建一行。

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

方法follow!需要id(一个数字,假设Friend模型遵循rails默认值)作为参数,但你传递的是完整的post_params 这一行中的哈希值:

if current_usuario.follow!(post_params)

如果您检查 post_params 的值,您会看到它是一个散列,类似于:

{ friend_id: 3 }

但是你只想通过3;所以,要解决这个问题,只需传递 friend_id 值(即 post_params[:friend_id]):

if current_usuario.follow!(post_params[:friend_id])

或者:

if current_usuario.follow!(params[:usuario][:friend_id])