2017-09-01 62 views
1

我試圖從API調用更新所有市場數據。使用方法更新Rails中的關聯對象

我有一個包含許多市場的平臺。市場有高,低,最新價格等。

我無法遍歷關聯的集合並調用一個方法來更新。也許我的整個結構都不正確,我不確定。

我認爲使用market.update方法刷新API調用數據是有意義的。

class MarketsController < ApplicationController 
    def update 
    @platform = Platform.find(params[:platform_id]) 
    @market = @platform.markets.find(params[:id]) 
    @market.api_get_market_summary 
    @market.save 
    redirect_to @market.platform 
    end 

其中在平臺視圖

<% @platform.markets.each do |market| %> 
     <%= market.market_name %> 
     <%= market.high %> 
     <%= market.low %> 
     <%= link_to 'Update', [market.platform, market], 
       :method => :put %> 
    <% end %> 

我試過在平臺控制器每個組合工作正常,但我不知道我應該怎麼做,以更新平臺的所有市場。

class PlatformsController < ApplicationController 
    def update 
    @platform = Platform.find(params[:id]) 
    @platform.markets.each do |market| 
     market.update(:id => market.id) # this obviously doesn't work 
    end 
    redirect_to @platform 
    end 

我應該用update_attributes函數更新這裏的所有屬性嗎?

當創建對象時,我會調用市場API更新,以便數據在此處被初始化,這非常棒。

我應該怎麼辦?

另一部分,如果我添加了另一個平臺,我將如何處理這個人使用的不同API請求?

回答

0

具有以下關係Platform --- has_many --- Market,如果你想在市場的集合執行的操作,你有沒有考慮在Platform模型添加callback

class Platform < ApplicationRecord 
    has_many :markets 
    after_save :update_markets 

    ... 

    private 

    def update_markets 
    markets.each do |market| 
     ... 
    end 
    end 
end 

注意:

after_save的運行都在創建和更新,但總是後的更爲具體的回調after_create和after_update,無論在哪個宏調用被執行的順序。

我不知道什麼是你想在這裏做market.update(:id => market.id),但如果你在所有的市場僅更新一個記錄考慮update_allhere's a good source

另一部分,如果我增加了一個平臺,我將如何處理這個人使用的不同的API請求?

通過添加其他平臺的新Platform對象被創建並存儲不同的ID,當請求命中控制器:

@market = @platform.markets.find(params[:id])

另外,還要考慮@market = Market.find(params[:id])代替上面。

+0

該回調適合罰款。謝謝。我使用Platform控制器的更新方法遍歷每個市場並更改觸發包含API調用的回調函數的屬性。 –

-1

您可以添加到您的平臺模型

accepts_nested_attributes_for :markets