据我所知,我们在方法new使用了一个实例变量
def new @article = Article.new end因为这个变量也用在new.html.erb 。 (如果我错了,请纠正我)。
但是为什么我们在create方法中使用实例变量? 在create方法之外还有哪些地方使用? 我们不能只使用局部变量article而不是实例变量@article吗?
def create article = Article.new(article_params) if article.save flash[:success] = "Article created successfully!" redirect_to articles_url else render 'new' end end private def article_params params.require(:article).permit(:title, :body) endAs far as I understand we use namely an instance variable in the method new
def new @article = Article.new endbecause this variable is used in new.html.erb too. (Please correct me if I am wrong).
But why do we use an instance variable in the create method? Where else is it used outside the create method? Can't we just use a local variable article instead of the instance variable @article?
def create article = Article.new(article_params) if article.save flash[:success] = "Article created successfully!" redirect_to articles_url else render 'new' end end private def article_params params.require(:article).permit(:title, :body) end最满意答案
你不能,因为@article变量也用在new.html.erb文件中,当article未成功保存时呈现。
所以你会得到(据我记得的)错误undefined method 'model_name' for nil:NilClass 。
You can't, because @article variable is also used in new.html.erb file, rendered when article isn't saved successfully.
So you'll get (as far as I remember) error undefined method 'model_name' for nil:NilClass.
更多推荐
发布评论