首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >让一个增量函数工作的正确方法是什么?

问让一个增量函数工作的正确方法是什么?
EN

Stack Overflow用户
提问于 2016-12-18 20:30:14
回答 1查看 40关注 0票数 0

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

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

下面是我的模型中的"another_one“函数(我尝试了一些方法)

代码语言:javascript
复制
  def another_one
    @number = self.class.where(:novel => @novel).count.to_i
    @number.increment
  end

这是控制器

代码语言:javascript
复制
  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

我做错了什么?

提前谢谢你

EN

回答 1

Stack Overflow用户

发布于 2016-12-18 20:57:04

您调用的anoter_one -这是another在@chapter.chapter_number值上的拼写错误-而不是模型。

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41208337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档