检测多个条件

Detect multiple conditions

我正在尝试使用 Sinatra 创建一个简单的 wine web 应用程序。我的 Wine 模型中的键是 "vintner"、"vintage" 和 "varietal"。年份是一个整数。我还有一个 Note 模型,供用户添加注释(目前以逗号分隔,稍后将计划变得更强大......)。

这是我在 WineController 中的 POST 操作:

post '/wines' do
  if params[:wine] == ""
    erb :'wines/new'
  else
    @wine = current_user.wines.new(params[:wine])
    @wines = current_user.wines

    if @wines.detect{ |wine| wine.vintner.downcase == 
      @wine.vintner.downcase && wine.varietal.downcase == 
      @wine.varietal.downcase && wine.vintage == @wine.vintage }
      flash[:message] = "That wine is already in your cellar! Add another."
      erb :'/wines/new'
    elsif !params[:note][:name].empty?
      params[:note][:name].split(", ").each{ |user_note| @wine.notes << 
        Note.find_or_create_by(:name => user_note) }
    end
  end

  @wine.save
  redirect to "/wines"
end

我想要完成的是 "if there is already a wine with that vintner, varietal, and vintage, don't create it and redirect back to the 'new' view with said message. Otherwise, add the notes to the that wine instance, save, and redirect to '/wines/index'"。

相反,酒会保存(但笔记不会保存),我会被重定向到“/wines/index”并显示上述消息。所以,这很奇怪。

我的主要问题是,我如何根据三个或更多标准进行检测(使用检测或任何其他方法)。另外,如果有人对我的笔记做错了什么有任何见解,我很乐意听到!谢谢!!

正如目前所写的行

@wine.save
redirect to "/wines"

在块最底部的所有条件之外,因此即使满足条件 params[:wine] == "",代码也会 运行,在这种情况下它会出错,因为 @wine 未设置。

尝试将该代码移动到 elsif !params[:note][:name].empty? 分支,然后它应该只 运行 当您需要创建新酒时。