Create方法中的实例变量与局部变量(Instance variable vs local variable in the Create method)

编程入门 行业动态 更新时间:2024-10-25 10:27:05
Create方法中的实例变量与局部变量(Instance variable vs local variable in the Create method)

据我所知,我们在方法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) end

As far as I understand we use namely an instance variable in the method new

def new @article = Article.new end

because 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.

更多推荐

本文发布于:2023-08-07 13:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   局部   实例   方法   Create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!