使用Method更新Rails中的关联对象

时间:2017-09-01 12:22:35

标签: ruby-on-rails api

< p>我尝试更新API调用中的所有市场数据。 < / p为H. < p>我有一个包含许多市场的平台。市场有高,低,最新价格等。< / p> < p>我无法遍历关联的集合并调用方法进行更新。也许我的整个结构不正确,我不确定。< / p> < p>我认为使用market.update方法通过API调用刷新数据是有意义的。< / p> < pre>< code> class MarketsController< ApplicationController的   def更新     @platform = Platform.find(params [:platform_id])     @market = @ platform.markets.find(params [:id])     @ market.api_get_market_summary     @ market.save     redirect_to @ market.platform   结束 < /代码>< /预> < p>在平台视图中工作正常< / p> <预><代码> <%@ platform.markets.each do | market | %GT;       <%= market.market_name%>       <%= market.high%>       <%= market.low%>       <%= link_to'更新',[market.platform,market],               :method => :put%>   <%end%> < /代码>< /预> < p>我已尝试过平台控制器中的所有组合,但我不知道应如何更新平台中的所有市场。< / p> < pre>< code>类PlatformsController< ApplicationController的   def更新     @platform = Platform.find(params [:id])     @ platform.markets.each做|市场|       market.update(:id => market.id)#这显然不起作用     结束     redirect_to @platform   结束 < /代码>< /预> < p>我应该使用update_attributes函数更新此处的所有属性吗?< / p> < p>我在创建对象时调用市场API更新,以便在那里初始化数据,这很好。< / p> < p>我应该怎么做?< / p> < p>另一部分,如果我添加了另一个平台,我将如何处理此人使用的不同API请求?< / p>

2 个答案:

答案 0 :(得分: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_all here's a good source

  

另一部分,如果我添加了另一个平台,我将如何处理这个人使用的不同API请求?

通过添加另一个平台,当请求到达您的控制器时,将创建一个新的Platform对象,并使用不同的ID进行存储:

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

另外,请考虑@market = Market.find(params[:id])而不是上述内容。

答案 1 :(得分:-1)

您可以将其添加到您的平台型号

accepts_nested_attributes_for :markets
相关问题