[英]What is the proper way to make an increment function work?
I'm creating a website that let people read short stories in several chapters. 我正在创建一个网站,使人们可以阅读几章中的短篇小说。 For this, I nested a chapter scaffold inside a novel scaffold, and linked (novel has_many :chapters, chapters belongs_to :novel) them both together. 为此,我在一个新颖的脚手架中嵌套了一个章脚手架,并将它们链接在一起(novel has_many:章,章属地属于:novel)。 However I'm trying to get the chapter's number inside the URL (instead of the id, which never decreases). 但是,我试图获取URL中的章节编号(而不是ID,它永远不会减少)。 Setting the chapter as is is not a problem, but I'd like to automate the chapter number without my users needing to add it themselves. 将章设置为原样不是问题,但是我想使章号自动化,而无需用户自己添加。
To do so, I figured that all I needed was to get how many chapter the current novel had by checking self.class.where(:novel_id => @novel).count
. 为此,我认为我所需要的只是通过检查self.class.where(:novel_id => @novel).count
来获得当前小说的篇章。 At this point, I have no issues, however it gets complicated when I try to increment this number, I get the error: undefined method 'anoter_one' for 0:Fixnum
在这一点上,我没有问题,但是当我尝试增加此数字时,它变得复杂,我得到了错误: undefined method 'anoter_one' for 0:Fixnum
Here is my "another_one" function inside my model (I tried some things) 这是模型中的“ another_one”函数(我尝试了一些操作)
def another_one
@number = self.class.where(:novel => @novel).count.to_i
@number.increment
end
Here is the controller 这是控制器
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
What am I doing wrong ? 我究竟做错了什么 ?
Thank you in advance 先感谢您
Your calling anoter_one
- which is a misspelling of another
on the value of @chapter.chapter_number
- not the model. 您的通话anoter_one
-这是一个拼写错误another
上的价值@chapter.chapter_number
-不是模型。
One way to solve this is by using an 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
In order for the callback to be called properly you want to build the associated items off the parent: 为了正确调用回调,您需要从父项构建关联项:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.