【问题标题】:Ruby on rails model method is not getting executed in controllerRuby on rails 模型方法未在控制器中执行
【发布时间】:2012-08-14 13:30:31
【问题描述】:

posts_controller.rb 销毁方法

def destroy

    if !request.xhr?
        render_404
        return
    end

    if user_signed_in?

        if Post.exists?(:post_id => params[:id])

                if Post.post_is_mine(params[:id], current_user.id)

                    @return = { :error => false, :response => "Post deleted" }

                else
                    @return = { :error => true, :response => 'You are not allowed to perform this action.' }
                end

            else
                @return = { :error => true, :response => 'This post doesn\'t exist.' }
            end

        else
            @return = { :error => true, :response => 'Please login before you delete a post.' }
        end

    render :json => ActiveSupport::JSON.encode( @return )

end

post.rb

  def self.post_is_mine(post_id, user_id)
    #where(:user_id => user_id, :post_id => bucket_id)
    where("user_id = ? and post_id = ?", user_id, bucket_id)
  end

当我在销毁帖子时检查正在运行的查询时,我只能看到要运行的 .exists? 而不是 .post_is_mine,它只是通过 因为它返回 TRUE

我尝试了其他几个名称作为方法,因为某些事情可能会导致问题,甚至只是尝试使用 .post_is_mine 的 if 语句,但仍然没有运行查询

关于我如何使用 where 子句的模型会不会有问题?

【问题讨论】:

    标签: ruby-on-rails activerecord methods model execute


    【解决方案1】:

    是的。 #where 返回一个 ActiveRecord 关系,用于生成您的查询。该关系不会在您的代码中进行评估,因此来自.post_is_mine 的查询将永远不会被执行。 if Post.postis mine(params[:id], current_user.id) 返回 true,因为 Relation 对象不是 nil

    您真正想要的是在post_is_mine 方法中使用exists?

    def self.post_is_mine(post_id, user_id)
      exists?(:user_id => user_id, :post_id => bucket_id)
    end
    

    编辑:

    我很好奇我的答案和 Pavling 的答案之间的区别。对于其他想知道的人:

    #exists? 使用SELECT 1 FROM ... 执行 SQL 语句

    #any? 使用SELECT COUNT(*) FROM ... 执行 SQL 语句

    实际上两者之间可能没有太大区别,但一些粗略的基准表明#any? 更快(在 OSX 上使用 AR 3.2.6 和 Postgresql 9.1)

    【讨论】:

    • 感谢您提供的扩展信息,真的帮助我了解了那里的差异
    【解决方案2】:

    “where”将返回一个空集合,其评估结果为真。您需要添加一个检查以查看其中是否有任何记录以获得正确的真/假。

    def self.post_is_mine(post_id, user_id)
      where("user_id = ? and post_id = ?", user_id, bucket_id).any?
    end
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多