如果没有模型文件,该表如何更新?

时间:2010-06-24 19:20:56

标签: mysql ruby-on-rails ruby syntax

我正在尝试手动更新Spree中的数据库,但它没有模型文件。我想知道如何在option_values_variants表中进行CRUD。

该代码使用了James Golick的资源控制器,但我希望不用。

模型/ option_value.rb

class OptionValue < ActiveRecord::Base
  belongs_to :option_type
  acts_as_list :scope => :option_type
  has_and_belongs_to_many :variants
end

控制器/管理/ variants_controller.rb

class Admin::VariantsController < Admin::BaseController
  resource_controller
  belongs_to :product

  new_action.response do |wants|
    wants.html {render :action => :new, :layout => false}
  end

  create.before :create_before

  # redirect to index (instead of r_c default of show view)
  create.response do |wants| 
    wants.html {redirect_to collection_url}
  end

  # redirect to index (instead of r_c default of show view)
  update.response do |wants| 
    wants.html {redirect_to collection_url}
  end

  # override the destory method to set deleted_at value 
  # instead of actually deleting the product.
  def destroy
    @variant = Variant.find(params[:id])

    @variant.deleted_at = Time.now()
    if @variant.save
      self.notice = I18n.t("notice_messages.variant_deleted")
    else
      self.notice = I18n.t("notice_messages.variant_not_deleted")
    end

    respond_to do |format|
      format.html { redirect_to admin_product_variants_url(params[:product_id]) }
      format.js  { render_js_for_destroy }
    end
  end

  private 
  def create_before 
    option_values = params[:new_variant]
    option_values.each_value {|id| @object.option_values << OptionValue.find(id)}
    @object.save
  end

  def collection
    @deleted =  (params.key?(:deleted)  && params[:deleted] == "on") ? "checked" : ""

    if @deleted.blank?
      @collection ||= end_of_association_chain.active.find(:all)
    else
      @collection ||= end_of_association_chain.deleted.find(:all)
    end
  end
end

我认为这与models / option_value.rb有关:has_and_belongs_to_many:variants行。但是如何关联两个项目?

1 个答案:

答案 0 :(得分:1)