Ruby on rails 返回布尔值的rails创建方法
我是Ruby on Rails的初学者,对于这个愚蠢的问题我深表歉意,但我已经搜索了一整天,仍然坚持着:( 我有一个模型方法可以将文件excel从计算机导入web,第一行包含表列,下一行包含要保存到数据库的记录集合。如果可以将所有记录保存到数据库,我尝试返回true,否则返回false,如下所示:Ruby on rails 返回布尔值的rails创建方法,ruby-on-rails,methods,import,return-value,dry,Ruby On Rails,Methods,Import,Return Value,Dry,我是Ruby on Rails的初学者,对于这个愚蠢的问题我深表歉意,但我已经搜索了一整天,仍然坚持着:( 我有一个模型方法可以将文件excel从计算机导入web,第一行包含表列,下一行包含要保存到数据库的记录集合。如果可以将所有记录保存到数据库,我尝试返回true,否则返回false,如下所示: def save message = if Item.import(params[:file]) "success" else
def save
message = if Item.import(params[:file])
"success"
else
"failure"
end
redirect_to import_items_path, notice: t(message)
end
型号
def self.import(file)
spreadsheet = open_spreadsheet(file) //another method to read file
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
item= find_by_id(row["id"]) || new
item.attributes = row.to_hash.slice(*accessible_attributes)
if item.invalid?{
return false;
break
}
else item.save end
end
end
并在控制器中调用它:
def save
if (Item.import(params[:file]))
redirect_to import_items_path, notice: t("success")
else redirect_to import_items_path, notice: t("fails")
end
end
但当我导入时,它没有返回真/假(总是将“success”设置为flash.notice)
我把它叫做这样一个变量
@test = Item.import(params[:file])
并将其发送到flash.notice,发现该方法总是返回如下字符串
“2..xx”(其中xx是文件中的多行)
我打电话是不是有些奇怪???请帮帮我…thks 1st获得任何类型的答案如果没有遇到无效的
项
,则您的导入
方法不会返回true
要解决此问题,请替换:
if item.invalid?{
return false;
break
}
else taisan.save end
end
end
与:
如果遇到无效的项目
,则会立即返回false
,否则返回true
另一方面,您可以像这样保留保存
功能:
def save
message = if Item.import(params[:file])
"success"
else
"failure"
end
redirect_to import_items_path, notice: t(message)
end
如果未遇到无效的
项,则导入方法不会返回true
要解决此问题,请替换:
if item.invalid?{
return false;
break
}
else taisan.save end
end
end
与:
如果遇到无效的项目
,则会立即返回false
,否则返回true
另一方面,您可以像这样保留保存
功能:
def save
message = if Item.import(params[:file])
"success"
else
"failure"
end
redirect_to import_items_path, notice: t(message)
end
是的,这很有效!!!我编辑了一点,因为我在创建问题时犯了一些错误,我的坏xD。顺便说一句,你的回答让我意识到我的方法很奇怪(可能是“因为我刚从C#移动到Ruby”),非常感谢John。关于注意:
因为我在我的web中使用了另一种语言,所以我将使用类似于't'的区域设置(“flash.import_msg”)`和t(“flash.import_error”)
,所以我这样写。是吗?是的,这是工作!!!我编辑了一点,因为我在创建问题时犯了一些错误,我糟糕的xD.Btw,你的回答帮助我意识到我的方法很奇怪(可能是因为我刚从C转到Ruby)非常感谢John。关于注意:
因为我在我的网站上使用了另一种语言,所以我将使用't(“flash.import\u msg”)和t(“flash.import\u error”)
,所以我这样写。对吗?