【问题标题】:Checking if instance of model already exists with certain paremeters使用某些参数检查模型实例是否已经存在
【发布时间】:2014-05-19 01:15:09
【问题描述】:

在我的应用程序中,我想检查是否存在与评论模型具有相同艺术家和日期字段的音乐会模型。如果有,我想将评论添加到音乐会,如果没有,那么我想创建一个新的音乐会并进行评论,因为音乐会有_许多评论和评论属于_to 音乐会...

所以我写了一个存在?我的 Concert 控制器中的功能:

def exists(@artist, @date)?
    @concert_exists = @concerts.find_by_artist_and_date(artist: @artist, date: @date)
    if @concert_exists.nil?
        return false
    else
        return true
    end
  end

然后在我的审核控制器中,我尝试为其创建功能执行此操作:

def create

    if Concert.exists(review_params[:artist], review_params[:date])?
      #add review to this concert 
    else
      @concert = Concert.create(:artist => "artist", :venue => "venue", :date => "2014-2-2")
      @review = @concert.reviews.create(review_params) 
      @concert.artist = @review.artist
      @concert.venue = @review.venue
      @concert.date = @review.date
      @concert.save
    end
end

我不断收到一个错误提示

“语法错误,意外的keyword_else”

我的实现是否不正确,是否有更简单的方法来做我正在尝试的事情?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model exists database-relations


    【解决方案1】:

    我想你想写:

    def exists?(@artist, @date)
    

    和:

    if Concert.exists?(review_params[:artist], review_params[:date])
    

    更改问号的位置。

    【讨论】:

    • 你说得对,但如果 Concert.exists?(review_params[:artist], review_params[ :日期])
    【解决方案2】:

    Rails 已经有一种方法可以为您做到这一点find_or_create_by,因此您无需重新发明轮子

    @concert = Concert.find_or_create_by(artist: @artist, venue: "venue", date: @date)
    @concert.reviews.create(review_params)
    

    【讨论】:

    • 那么基于此,我如何检查是否创建了新的音乐会?
    • @user2739431 rails 文档说:find_or_create_by 方法检查是否存在具有属性的记录。如果没有,则调用 create,您不妨阅读文档以更好地了解它的作用,您还可以在传递给方法的哈希中包含 venue: "venue"
    • 对,但我需要知道它是否已创建,以便我可以为已存在的评论添加评论
    • @user2739431 我已经更新了我的答案,以准确反映你想要什么
    • @user2739431 是否正在保存@concert??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多