【问题标题】:How pass params and save in db如何传递参数并保存在数据库中
【发布时间】:2016-02-17 02:06:24
【问题描述】:

有关系:

(我的代码是葡萄牙语)

订购

class Pedido < ActiveRecord::Base
  belongs_to :pessoa

class Pessoa < ActiveRecord::Base
  belongs_to :usuario
  has_many :enderecos
  has_many :pedidos

  accepts_nested_attributes_for :enderecos
end

用户

class Usuario < ActiveRecord::Base

  has_many :pessoas
  has_many :pedidos, through: :pessoas

end

carrinhos_controller.rb

def checkout
    @pedido = current_usuario.pedidos.build
  end

在迁移中Personusuario_idOrderpessoa_id 和其他... 当我完成一个订单时,pessoa_id 为空并且没有保存在数据库中,为什么??

更多代码: pedidos_controller.rb

class PedidosController < ApplicationController
  before_action :authenticate_usuario!

  # Criar pedido
  def create
    @pedido = current_usuario.pedidos.build(pedido_params)
    if @pedido.save
      @pedido.construir_cache_item_carrinho(carrinho_atual)
      @pedido.calcular_total!(carrinho_atual)
      carrinho_atual.limpar!
      #OrdemDeServico.new(carrinho_atual, @pedido).encomendar_pedido!
      redirect_to pedido_path(@pedido.token)
    else
      render "carrinho/checkout"
    end
  end

【问题讨论】:

  • 为什么UserPerson 是不同的模型?
  • 因为不等于,用户因人而异,各有各的功能

标签: ruby-on-rails ruby ruby-on-rails-4 relationship


【解决方案1】:

使用此代码:

def checkout
 @pedido = current_usuario.pedidos.build
 @pedido.save
end

如果您使用buildnew,那么您必须在此之后使用save 方法。否则可以直接使用create方法。

【讨论】:

    【解决方案2】:

    build 不保存到数据库。之后保存(@pedido.save)或尝试@pedido = current_usuario.pedidos.create

    【讨论】:

    • 对不起,我忘记了其他部分...请现在看
    【解决方案3】:

    我想您正在使用嵌套表单之类的东西来发布参数。我经常使用nested_form gem by Ryan Bates

    如果您仔细查看用法,您会发现一些有用的见解。 还要注意 strong_parameters:需要在控制器中声明您想要允许的参数。

    【讨论】:

    • 谢谢,但是使用这个 gem 我的错误继续......我需要做一些东西来保存数据库中的 pessoa_id。它还为空。
    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多