【问题标题】:include and If statement inside a for each在 for each 中包含和 If 语句
【发布时间】:2016-01-02 17:38:33
【问题描述】:

客户端最多可以上传三个文件。我想根据他们选择的描述设置文件的状态。上传可以正常工作,静态状态也可以,但动态会引发错误。

def build_document_objects
  [:first, :second, :third].each do |doc|
    d = "#{doc}_document"
    if self.send("#{d}_type") == "this Type"
      doc_status = 'one'
    else
      doc_status = 'two'
      self.send("#{d}=", user.documents.new(
        description: "Foo",
        file: self.send("#{d}_file"),
        document_type: self.send("#{d}_type"),
        status: doc_status
      ))
    end
  end
end

当我运行它时,我得到以下异常:

undefined method `save'' for nil:NilClass')) 

如果我这样做:

 def build_document_objects
 [:first, :second, :third].each do |doc|
  # "first_document"
  d = "#{doc}_document"
  if self.send("#{d}_type") == "this Type"
  doc_status = 'one'
else
  doc_status = 'two'
  end  # change  where the IF ends
  self.send("#{d}=", user.documents.new(
    description: "Foo",
    file: self.send("#{d}_file"),
    document_type: self.send("#{d}_type"),
  status: doc_status
    ))
end
end

如果文件描述不是this type,记录将被保存。但是,与:

    if self.send("#{d}_type") == "this Type"

我得到了例外。记录不会被保存,因为没有状态存在。

【问题讨论】:

  • 错误是记录不会保存
  • ...特别是异常消息和它发生的行。请编辑以将该信息添加到问题中,而不是在评论中详细说明。
  • ...以及它发生的行。错误消息包含有价值的信息。你需要仔细研究它们!
  • 想必还有其他几个方法你没有给我们展示过,比如:first_document_type。由于您提供给我们的代码中没有方法:save(引发异常),因此错误似乎发生在其他方法之一中。如果是这样,我们将不得不看到其他代码。
  • “我得到异常记录不会保存,因为没有状态存在”......这是一个非常模糊的句子。您能否编辑您的问题以包含异常/错误的确切措辞,包括(根据 Cary 要求)行号...这将是异常消息的一部分。

标签: ruby if-statement each


【解决方案1】:

看来我疯了

def build_document_objects
[:first, :second, :third].each do |doc|
# "first_document"
d = "#{doc}_document"
if self.send("#{d}_type") == "this Type"
doc_status = 'one'
else
doc_status = 'two'
end  # change  where the IF ends

 self.send("#{d}=", user.documents.new(

description: "Foo",
file: self.send("#{d}_file"),
document_type: self.send("#{d}_type"),

status: doc_status

))

end

end

工作正常 if 只需要正确地出现在方法中即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多