简体   繁体   English

Rails如何知道采用哪个变量

[英]How does Rails know which variable to take

Beginner in Rails here by following tutorial by mackenziechild.me. 通过遵循Mackenziechild.me的教程,可以在这里开始学习Rails。 For example, I have created a PostController with lots of method. 例如,我创建了具有许多方法的PostController。 However, what confuses me is they seem to have the same variable @post. 但是,令我困惑的是它们似乎具有相同的@post变量。 In this case, how do the program actually knows which correct variable it needs to get? 在这种情况下,程序实际上如何知道需要获取哪个正确的变量? Don't they will get confused when the application is running? 他们不会在应用程序运行时感到困惑吗?

class PostsController < ApplicationController
    def index
        @posts = Post.all.order('created_at DESC')
    end

    def new
        @post = Post.new        
    end 

    def create
        @post = Post.new(post_params)

        if @post.save
            redirect_to @post
        else
            render 'new'
        end     
    end

    def show
        @post = Post.find(params[:id])
    end 

    private

    def post_params
        params.require(:post).permit(:title, :body)
    end     
end

In rails each action like index, new, show etc which is a get method has their corresponding views in the corresponding folder named as the controller name. 在rails中index, new, show etc作为get方法的每个动作(如index, new, show etc在相应的文件夹中都有其对应的视图,称为controller名称。

So when a action is called then their particular view is called. 因此,当调用一个动作时,就会调用其特定的视图。

Eg:- 例如:-

def index
    @posts = Post.all.order('created_at DESC')
end

Their should be a view as index.html.erb in the folder app/views/posts/ and in that view the instance variable @posts will be accessible. 它们应该是app/views/posts/文件夹中的index.html.erb app/views/posts/ ,在该视图中,实例变量@posts可以访问。

In this line Post.all.order('created_at DESC') , Post model query the database and fetch all the record from the table as posts and also sort the record in descending order of created _at column. 在此行Post.all.order('created_at DESC')Post模型查询数据库,并从表中获取所有记录作为posts并以created _at列的降序对记录进行排序。

Post model is inherited from ActiveRecord::Base , due this it can map the posts table in the database. Post模型继承自ActiveRecord::Base ,因此它可以映射数据库中的posts表。

def show
    @post = Post.find(params[:id])
end 

In the above show method it is querying only one record whose id is in params[:id] . 在上述show方法中,它仅查询id为params[:id]一条记录。

Instance variables are accessible in the views so in @post = Post.find(params[:id]) @post can be used in its corresponding view as show.html.erb in app/views/posts/ 实例变量可在视图中访问,因此在@post = Post.find(params[:id]) @post可以在其对应的视图中用作app/views/posts/ show.html.erb

Ikanyu, the @post variable is an instance variable ie its scope is limited to the method it is defined in. So the @post variable defined in new method is different from the one defined in show and the hence these different variables are accessed in the views without any issue. Ikanyu, @post变量是一个实例变量,即,其范围仅限于其定义的方法。因此,新方法中定义的@post变量与@post定义的变量不同,因此可以在视图没有任何问题。

For more info as to how these variables are passed into view refer to this link: 有关如何将这些变量传递到视图中的更多信息,请参见以下链接:

How are Rails instance variables passed to views? Rails实例变量如何传递给视图?

I have created a PostController with lots of method. 我用很多方法创建了一个PostController。 However, what confuses me is they seem to have the same variable @post. 但是,令我困惑的是它们似乎具有相同的@post变量。 In this case, how do the program actually knows which correct variable it needs to get? 在这种情况下,程序实际上如何知道需要获取哪个正确的变量? Don't they will get confused when the application is running? 他们不会在应用程序运行时感到困惑吗?

When your browser requests a page, the request is routed to ONE of the methods you defined. 当浏览器请求页面时,请求将路由到您定义的方法之一。 That method executes, and that method sets the value of @post. 该方法执行,该方法设置@post的值。 After the response is sent to the browser, rails destroys all the variables that were created. 将响应发送到浏览器后,rails破坏所有已创建的变量。

but we have Post.new, Post.new(post_params), Post.find(params[:id]) I came from a Java background. 但是我们有Post.new,Post.new(post_params),Post.find(params [:id])我来自Java背景。 so this is quite confusing me. 所以这让我很困惑。 They area all being assigned to the same @post 它们都被分配到相同的@post

In Java, you can certainly assign three things to the same variable: 在Java中,您当然可以将三件事分配给同一变量:

int x = 1;
x = 2;
x = 3;
System.out.println(x);  #=>3

And, if you have a class named Post you can also assign three different Post objects to the same variable: 而且,如果您有一个名为Post的类,则还可以将三个不同的Post对象分配给同一变量:

    Post p = new Post("hello");
    System.out.println(p.getText());
    p = new Post("world");
    System.out.println(p.getText());
    p = new Post("goodbye");
    System.out.println(p.getText());  #=>goodbye

Each of: Post.new , Post.new(post_params) , and Post.find(params[:id]) returns a Post object; Post.newPost.new(post_params)Post.find(params[:id])一个都返回一个Post对象; additionally they are being assigned to the same variable, so why are you confused by that coming from a Java background ? 另外,它们被分配给相同的变量,那么为什么您对Java来的变量感到困惑呢?

However, you should also note that Rails uses a language called ruby under the hood, and in ruby variables do not have types, and they do not have to be declared. 但是,您还应该注意,Rails在幕后使用了一种称为ruby的语言,并且在ruby中变量没有类型,也不必声明。 So, in ruby you can assign different types to the same variable: 因此,在ruby中,您可以为同一变量分配不同的类型:

some_var = "hello"  #String
some_var = 10  #Integer
some_var = [1, 2, 3]  #Array
some_var = {a: 1, b: 2}  #Hash

If you said that you were confused by something like that, it would make more sense. 如果您说自己被类似的东西弄糊涂了,那将更有意义。 Yet, what's there to be confused about by even that? 但是,即使如此,还有什么让我感到困惑的呢? There are two simple rules: 有两个简单的规则:

  1. Variable names do not have types. 变量名称没有类型。
  2. As a result, you do not have to declare variables. 因此,您不必声明变量。

Earlier, I said this: 之前,我这样说:

When your browser requests a page, the request is routed to ONE of the methods you defined. 当浏览器请求页面时,请求将路由到您定义的方法之一。 That method executes, and that method sets the value of @post. 该方法执行,该方法设置@post的值。 After the response is sent to the browser, rails destroys all the variables that were created. 将响应发送到浏览器后,rails破坏所有已创建的变量。

Internally, the way that works is: 在内部,工作方式是:

  1. When a url is routed to a certain controller, rails creates an instance of that controller class: 当将URL路由到某个控制器时,rails会创建该控制器类的实例:

    obj = PostsController.new

  2. Rails uses the controller instance to call one of the methods defined in the controller class(the method is determined by the routing): Rails使用控制器实例来调用在控制器类中定义的方法之一(该方法由路由确定):

    obj.show

(Just like in Java, there are ways to call a method when you have the name of the method as a String--and it's much easier in ruby.) (就像在Java中一样,当方法的名称为String时,有多种方法可以调用方法-在ruby中它要容易得多。)

  1. The method executes. 该方法执行。

  2. After the response is sent to the browser, rails destroys the controller instance: 响应发送到浏览器后,rails破坏控制器实例:

    obj = nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails如何知道要显示哪些属性? - How does Rails know which attributes to show? Rails 4如何知道要使用哪个清单文件? - How does rails 4 know which manifest file to use? Rails服务器如何知道要使用哪个route.rb? - How does a rails server know which route.rb to use? Rails应用程序如何知道在何处提取ENV变量? - How does a rails app know where to pull an ENV variable? Rails如何从Rails指南中知道在此示例中使用哪个控制器的“显示”操作? - How does Rails know which controller's “show” action to use in this example from Rails Guides? Rails如何选择要渲染的实例变量的版本? - How does rails choose which version of an instance variable to render? Rails:如何知道哪个路线将被称为 - Rails: How to know which route will be 'called' 渲染集合时,Rails如何知道要渲染哪个部分名称? - How does Rails know which partial name to render when rendering a collection? Rails如何知道表中的哪一列是相关表中的索引? - How does Rails know which column from a table is the index in a related table? 如果您的ruby on rails脚本中有多个错误,那么它如何知道显示哪个错误? - If you have more than 1 error in your ruby on rails script, how does it know which one do display?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM