0

我有表格“工具”和“借出”。

我使用 Rails3,当我创建借出时,我希望它将工具的属性状态更改为“U”。

这可能吗?

我试过模型借

 after_save :change_status

  def change_status
      tools.update_attribute(status, 'U')
  end

我也试过,在同一型号上:

 after_save :change_status

  def change_status
      self.tool.update_attribute(status, 'U')
  end

调试日志上没有成功或警告。

建议?

谢谢!:)

4

2 回答 2

0

借贷和工具是什么关系?如果 Lend has_many 工具,你将不得不做这样的事情:

def change_status
  tools.each { |tool| tool.update_attributes(status: 'U') }
end

另请注意,我正在使用 update_attributes 因为 update_attribute (单数)将很快被弃用。

顺便说一句,您应该在 Tool 中创建一个方法来更新属性,Lend 模型不应该知道如何将工具设置为借出。就像是

def loaned!
  update_attributes status: 'U'
end
于 2012-08-21T20:52:25.550 回答
0

首先,我假设您的 Lend 模型 has_many :tools

为了能够做类似的事情,tool.update_attribute你需要使用accepts_nested_attributes_for

看看这些链接,它们可能会让你走上正确的道路:
RailsCasts #196 Nested Model Form Part 1
Active Record Nested Attributes

希望这可以帮助。

于 2012-08-21T20:37:14.207 回答