我正在创建一个网站,让人们在几个章节中阅读短篇小说。为此,我在一个小说脚手架中嵌套了一个章节脚手架,并将它们链接在一起(小说has_many :章节,章节belongs_to :小说)。然而,我试图在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我做错了什么?
提前谢谢你
发布于 2016-12-18 20:57:04
您调用的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
endhttps://stackoverflow.com/questions/41208337
复制相似问题