Ruby on rails 保存新创建的对象

Ruby on rails 保存新创建的对象,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,在Rails控制器代码中 def create @post = Post.new(params[:post]) @post.random_hash = generate_random_hash(params[:post][:title]) if @post.save format.html { redirect_to @post } else format.html { render action: "new" } end end 定义的前两行是否应该放在@

在Rails控制器代码中

def create
  @post = Post.new(params[:post])
  @post.random_hash = generate_random_hash(params[:post][:title])
  if @post.save
    format.html { redirect_to @post }
  else
    format.html { render action: "new" }
  end
end
定义的前两行是否应该放在@post.save
中?如果未保存post,由
post.new
创建的post对象是否仍会放入数据库中

  • 如果
    @post.save
    ,定义的前两行是否应该放在里面

    当然不是。如果按照您的建议将其更改为以下内容:

    def create
      if @post.save
        @post = Post.new(params[:post])
        @post.random_hash = generate_random_hash(params[:post][:title])
        format.html { redirect_to @post }
      else
        format.html { render action: "new" }
      end
    end
    
    那就根本不起作用了。没有
    @post
    可以调用
    save

  • 如果未保存帖子,由
    post.new创建的
    post
    对象是否仍会放入数据库中

    当然不是。这就是保存的作用:将对象保存到数据库中。如果未在
    Post
    对象上调用
    save
    ,或者
    save
    返回
    false
    (由于验证失败而发生),则该对象未存储在数据库中
    Post.new
    只是在内存中创建一个新的
    Post
    对象,它根本不涉及数据库

  • 如果
    @post.save
    ,定义的前两行是否应该放在里面

    当然不是。如果按照您的建议将其更改为以下内容:

    def create
      if @post.save
        @post = Post.new(params[:post])
        @post.random_hash = generate_random_hash(params[:post][:title])
        format.html { redirect_to @post }
      else
        format.html { render action: "new" }
      end
    end
    
    那就根本不起作用了。没有
    @post
    可以调用
    save

  • 如果未保存帖子,由
    post.new创建的
    post
    对象是否仍会放入数据库中

    当然不是。这就是保存的作用:将对象保存到数据库中。如果未在
    Post
    对象上调用
    save
    ,或者
    save
    返回
    false
    (由于验证失败而发生),则该对象未存储在数据库中
    Post.new
    只是在内存中创建一个新的
    Post
    对象,它根本不涉及数据库