【问题标题】:What is the proper way to make an increment function work?使增量功能起作用的正确方法是什么?
【发布时间】:2016-12-18 12:30:14
【问题描述】:

我正在创建一个网站,让人们可以分几章阅读短篇小说。 为此,我在小说脚手架内嵌套了一个章节脚手架,并将它们链接在一起(小说 has_many :chapters, chapters belongs_to :novel)。 但是,我试图在 URL 中获取章节编号(而不是永远不会减少的 id)。按原样设置章节不是问题,但我想自动化章节编号,而不需要我的用户自己添加。

为此,我认为我所需要的只是通过检查self.class.where(:novel_id => @novel).count 来获取当前小说的章节数。在这一点上,我没有任何问题,但是当我尝试增加这个数字时它变得很复杂,我收到错误:undefined method 'anoter_one' for 0:Fixnum

这是我模型中的“another_one”函数(我尝试了一些东西)

  def another_one
    @number = self.class.where(:novel => @novel).count.to_i
    @number.increment
  end

这里是控制器

  def create
    @novel = Novel.find(params[:novel_id])
    @chapter = Chapter.new(chapter_params)
    @chapter.chapter_number.another_one
    @chapter.novel = @novel
    if @chapter.save
      redirect_to novel_chapter_path(@novel, @chapter), notice: 'Chapter was successfully created.'
    else
      render :new
    end
  end

我做错了什么?

提前谢谢你

【问题讨论】:

    标签: ruby-on-rails model increment


    【解决方案1】:

    您的呼叫 anoter_one - 是 another@chapter.chapter_number 值的拼写错误 - 而不是模型。

    解决此问题的一种方法是使用association callback

    class Novel
      has_many :chapters, before_add: :set_chapter_number
      def set_chapter_number(chapter)
        if chapter.chapter_number.blank? 
          chapter.chapter_number = self.chapters.size + 1
        end
      end
    end
    

    为了正确调用回调,您需要从父项构建关联项:

    def new
      @novel = Novel.find(params[:novel_id])
      @chapter = @novel.chapters.new
    end
    
    def create
      @novel = Novel.find(params[:novel_id])
      @chapter = @novel.chapters.new(chapter_params)
    
      if @chapter.save
        redirect_to [@novel, @chapter], notice: 'Chapter was successfully created.'
      else
        render :new
      end
    end
    

    【讨论】:

    • 感谢您的回答,我改编/粘贴了您的代码,但它不起作用。表单提交没有问题,但在数据库中,:chapter_number 没有获得任何新值。我是否想保留我的“another_one”(顺便说一句,打错了)功能?
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 2015-02-05
    • 2021-10-31
    • 2014-10-04
    • 1970-01-01
    • 2013-06-12
    • 2021-06-24
    • 2014-03-07
    相关资源
    最近更新 更多