未定义的方法“ value_changed?” -Ruby on Rails

时间:2019-07-19 04:42:20

标签: ruby-on-rails ruby-on-rails-5.1

我有一个Products控制器,可以添加新产品,编辑,更新等。但是,出现以下错误:

NoMethodError in ProductsController#create
undefined method `value_changed?' for #<Product:0x00007facd78b1f10> Did you mean? title_changed?

这是我的Products控制器:

class ProductsController < ApplicationController
  # add_breadcrumb "All products", :products_path, :only => %w(index show)
  # add_breadcrumb "Catalog", ""
  # add_breadcrumb "Category", ""

  before_action :set_product, only: [:show]

  # GET /products
  # GET /products.json
  def index
    search = params[:q].present? ? params[:q] : nil
    @products = if search
      Product.search(search)
    else
      Product.all
    end
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      flash[:success] = "New product was created."
      redirect_to root_path
    else
      flash[:alert] = "Something went wrong. Please try again or contact support."
      redirect_to root_path
    end

  end

  def destroy
  end

  def show
    # add_breadcrumb @product.name, @product
    @product_sellers = InventoryItem.all.includes(:seller).where(product_id: @product.id)
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.require(:product).permit(:title)
    end
end

表格:

= form_for @product, :html => { class: "form" } do |f|
 %div(class="ui-card")
   %div(class="ui-card_body")
     %div(class="form_row")
       = f.text_field :title
     %div(class="form_row")
       = f.submit "Save"

我在做什么错?非常感谢您的帮助和时间:)

PS:gem 'rails', '~> 5.1.6'

更新

型号:

class Product < ApplicationRecord   
  has_many :inventory_items, dependent: :delete_all
  has_many :sellers, :through => :inventory_items
  # has_and_belongs_to_many :categories


  after_commit :reindex_sellers
  after_save -> { product.reindex }, if: :value_changed? # reindex product manually when value is changed


  # Search products
  searchkick word_start: [:title], callbacks: :async

  def search_data
    {
      name: title,
      sellers_full_name: sellers.map(&:full_name),
      sellers_business_name: sellers.map(&:business_name),
      sellers_country: sellers.map(&:country_full_name)
    }
  end

  def reindex_sellers
    sellers.reindex # or reindex_async
  end

end

0 个答案:

没有答案