【问题标题】:Rails 3 How to find out find_or_create which action was triggeredRails 3 如何找出触发了哪个动作的 find_or_create
【发布时间】:2012-12-19 13:44:31
【问题描述】:

我刚刚遇到了我必须做的事情

find_or_create

where(attributes).first_or_create

正如this post 建议的那样。

但有件事我一直在想

有没有办法确定触发了哪个操作? (因为我想在创建时显示适当的通知)顺便说一句。我正在使用 Ruby 1.9.3

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    如果 ruby​​ 是 1.9.3+,则使用 __method__

    if ['new','include'].include? __method__ then
      ...
    else
      ...
    end
    

    【讨论】:

    • 又是你,迈克尔。感谢您的回答,您能否详细介绍一下如何在控制器中使用它?
    • 感谢 michael,现在看来 shweta 的方式更短了。但我会记住这一点
    【解决方案2】:

    我个人认为不要使用find_or_create,而是分别使用find和create,这样我认为它更干净和可扩展。

    例如,如果您想在创建记录后做更多的事情。而且我坚信一种方法应该做一件事的概念:),

    所以我会写这样的东西

    HTH

    【讨论】:

    • 我尝试按照迈克尔的建议使用__method__,但我对 ruby​​ 有点陌生,找不到解决方案。我想我可能会接受 shweta 的回答。你说得有道理。谢谢
    【解决方案3】:
    if Model.find_by_attributes(attributes)
      flash[:notice] = "record found"
    else
      Model.create(attributes)
      flash[:notice] = "record created"
    end
    

    【讨论】:

    • 谢谢。我也考虑过使用 if else ,但我有点想知道使用 find_or_createfirst_or_create 时的操作
    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2012-08-12
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多