2016-12-18 61 views
0

我正在创建一个网站,让人们在几章中阅读短篇小说。 为此,我在一个新的脚手架中嵌套了一章脚手架,并将它们连在一起(小说has_many:章节,章节belongs_to:小说)。 但是我试图在URL中获取章节的编号(而不是从未减少的编号)。按照原样设置章节不是问题,但是我希望自动化章节编号,而无需用户自行添加。为了做到这一点,我想我只需要通过检查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 

我在做什么错?

预先感谢您

回答

0

您的通话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 
+0

谢谢为了您的答案,我修改/粘贴了您的代码,但它不起作用。表单被提交没有问题,但在数据库中,:chapter_number没有得到任何新值。我想保留我的“another_one”(顺便提一下)功能吗? – Jaeger

相关问题