3

我有一个产品型号,我需要在 _form 视图中写入管理员想要插入的产品编号。我有另一个带有 Supply(产品数量)的表,所以在我的产品表中我没有属性数量,但我只有supply_id(链接我的两个产品和供应表)

由于我的产品表中没有数量,因此我在产品上使用了虚拟属性。

我不得不更改新的视图并在新的中编辑产品原因我想要字段数量但在编辑中我不想要(因为我使用另一个视图来执行此操作)所以,我删除了部分 _form 并创建了单独的看法。此外,我必须在产品控制器中设置,如果我想更新产品,我必须调用 set_quantity 回调,因为我必须插入一个“假”值来填充params[:product][:quantity]. 这是因为我在产品模型中的数量虚拟字段上设置了验证存在。我想知道,如果所有这个故事都是正确的(它有效,但我想要一个关于这个故事的编程设计的建议。因为我不喜欢我给出一个假值来填充数量字段的事实)更新产品)

控制器:

class ProductsController < ApplicationController
    include SavePicture 
    before_action :set_product, only: [:show, :edit, :update, :destroy]
    before_action :set_quantita, only: [:update]
    ....

    def set_quantita
       params[:product][:quantita]=2  #fake value for the update action
    end
    ....
end

模型:

class Product < ActiveRecord::Base
    belongs_to :supply ,dependent: :destroy
    attr_accessor :quantita
    validates :quantita, presence:true
end

你能说我是否有更好的方法来填充param[:product][:quantity]更新操作的情况?因为我不喜欢我给它的值 2。谢谢。

4

1 回答 1

11

attr_accessor您可以在产品模型上创建自定义 getter/setter,而不是使用。请注意,这些不受常规实例属性的支持。

您还可以在关联上添加验证,supply而不是虚拟属性。

class Product < ActiveRecord::Base
  belongs_to :supply ,dependent: :destroy
  validates_associated :supply, presence:true

  # getter method
  def quantita
    supply
  end

  def quantita=(val)
    if supply
      supply.update_attributes(value: val)
    else
      supply = Supply.create(value: val)
    end
  end
end

在 Ruby 中赋值实际上是通过消息传递完成的:

product.quantita = 1

将调用product#quantita=, 以 1 作为参数。

另一种选择是对供应使用嵌套属性

class Product < ActiveRecord::Base
  belongs_to :supply ,dependent: :destroy
  validates_associated :supply, presence:true
  accepts_nested_attributes_for :supply
end

这意味着Product接受supply_attributes- 属性的散列。

class ProductsController < ApplicationController

  #...
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def create
    # will create both a Product and Supply
    @product = Product.create(product_params)
  end

  def update
    # will update both Product and Supply
    @product.update(product_params)
  end

  private

  def product_params
    # Remember to whitelist the nested parameters!
    params.require(:product)
          .allow(:foo, supply_attributes: [:foo, :bar])
  end
  # ...
end
于 2015-06-18T13:23:15.450 回答