包含和if语句在每个内部

时间:2015-10-05 22:58:11

标签: 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 = '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"

我得到了例外。由于没有状态,因此不会保存记录。

1 个答案:

答案 0 :(得分:0)

看来我很疯狂

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

工作正常 如果只是需要在方法中正确。