2011-10-07 25 views
1

我有一個通用導入表,允許將csv文件加載到導入表中的不同列中。相同的導入表用於多種類型的導入,所以我不處理各個字段,直到用戶準備好並告訴我在哪裏處理它。我應該如何更新來自不同控制器(或模型)的一個模型(表格)

因此,在這種情況下,我有一個導入表,其中有許多單元格用於在捐助者表中創建(或更新)捐助者。如何將與import_table模型和控制器關聯的import_table數據發送到我的donors_controller的create方法?

的創建我donors_controller的方法:

 def create 
     # need to find donor by id if given, else use find_or_create_by_blahblahblah 
     unless @donor = Donor.find_by_id(params[:donor][:id]) 
      @donor = Donor.find_or_initialize_by_company_and_prefix1_and_first_name1_and_last_name1_and_address1(params[:donor]) 
     end 

     if @donor.new_record? 

      respond_to do |format| 
      if @donor.save 
       format.html { redirect_to @donor, notice: 'Donor was successfully created.' } 
       format.json { render json: @donor, status: :created, location: @donor } 
      else 
       format.html { render action: "new" } 
       format.json { render json: @donor.errors, status: :unprocessable_entity } 
      end 
      end  
     else 
      respond_to do |format| 
      if @donor.save 
       format.html { redirect_to @donor, notice: 'Donor already exists. Please edit donor if needed.'} 
       format.json { render json: @donor, status: :created, location: @donor } 
      else 
       format.html { render action: "new" } 
       format.json { render json: @donor.errors, status: :unprocessable_entity } 
      end 
      end 
     end 

     end 

然後在我的import_tables控制器我有這樣的方法:

def process_import 
    @import = ImportTable.find(params[:id]) 
    if @import.import_type == 'Prospects' 
    #do something here.... 
    elsif @import.import_type == 'Donations' 
    #do something here... 
    end 

end 

我不知道究竟我應該在#do something here...部位做。

我在想我應該從@import中挑選出正確的列,並將它們放在[:donor]數組中,並將它們發送給我的donors_controller的create方法,但我不確定如何做到這一點或者如果這是正確的方法。

回答

2

缺少的一環是,你需要去的類從它的名字..

有幾種方法可以做到這一點,例如以「EVAL」,而是一個更清潔,更簡單的方式做到這一點是:

# do something: 
    class_name = @import.import_type 
    klass = ActiveRecord.const_get(class_name) # now you have a reference to your class 

    #... then do whatever you like with your symbolic klass, e.g. create your new entry 
    # klass.find_or_create(...) , klass.find(1), klass.first , 
    # klass.create({attributes for new instance of klass}) 

這個工作這麼方便,因爲在你的模型,你做YourClass <的ActiveRecord :: Base的, 類是ActiveRecord的一部分模塊中,Ruby中的類是存儲在其定義的上下文中的常量(=在其模塊中),因此您可以查詢該上下文(例如ActiveRecord)並找到您的類。從ActiveRecord :: Base,你仍然可以做:

klass = Kernel.const_get(class_name) 

另請參閱: http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/

+0

我同意,這是正確的方法... –

1

如果你要一行一行,請保持你正在處理的行的數量。

然後在#do一些地區只需要調用Prospect.new,Donation.new等

驗證或保存它,並收集了由對象報告的所有錯誤,這樣就可以吐出他們回到具有發生錯誤的行號的用戶。

您不需要爲每種類型啓用特定的控制器方法。您的導入邏輯將基本上處理它。

相關問題