Ruby 在for each中包含和If语句

Ruby 在for each中包含和If语句,ruby,if-statement,each,Ruby,If Statement,Each,客户端最多可以上载三个文件。我想根据他们选择的描述设置文件的状态。上传工作正常,静态状态正常,但动态状态会引发错误 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 =

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

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
如果文件描述不是此类型的
,则将保存记录。然而,对于:

    if self.send("#{d}_type") == "this Type"
我有个例外。由于没有状态存在,记录将不会保存。

看来我疯了

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只需要正确地存在于方法中。

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