【问题标题】:Why do I create a new model object in two methods in a controller?为什么我要在一个控制器中用两种方法创建一个新的模型对象?
【发布时间】:2016-05-29 10:22:22
【问题描述】:

根据互联网的各个部分,我有以下代码:

控制器

class StudiesController < ApplicationController

    def new
        require_user
        @study = Study.new
    end

    def create
        @study = Study.new(study_params)
        if @study.save
            flash[:success] = "You made it!"
            redirect_to root_path
        else
            flash[:danger] = "Uh oh—something went wrong"
            redirect_to study_path
        end
    end
end

查看

<%= form_for(@study, url: {action: :create}, class: "study-form") do |f| %>
    <%= f.text_field :title %><br>
    <div class="btn-submit">
        <%= f.submit "I studied today!", class: "btn btn-primary margin-top" %>
    </div>
<%= end %>

它有效,但我的问题是:为什么我需要两次调用Study.new?如果我已经在new 中调用它,为什么还要在create 中调用它?

【问题讨论】:

  • 尝试删除url: {action: :create},你不需要那个。以及结束函数上的=

标签: ruby-on-rails forms ruby-on-rails-4 crud


【解决方案1】:

在新方法中创建的 Study 实例用于在视图中呈现 HTML。

当该 HTML 被发送到浏览器时,Study 的实例不再存在——它从未被保存过,只是为了帮助呈现 HTML 而创建的。

当从浏览器提交表单时,会传入参数以将值分配给要创建的实例,但首先必须创建一个新的 Study 实例来分配它们。

然后保存此实例。

【讨论】:

  • 据我了解,表单唯一做的事情是:1)使用这些参数为控制器的create方法创建{study: {title: "hello"} }等参数,2)POST。真的吗?还是表单做得更多?
  • 这非常正确,但是将这些项目添加到 HTML 表单是通过视图完成的,它使用初始化的对象来完成。
【解决方案2】:

当您在 new 方法中使用 Study.new 创建新对象时,它用于在保存之前创建新记录并呈现新表单。之后,当您在 create 方法中使用 Study.new(study_params) 时,它将根据表单提交的值构建对象,并将数据保存在数据库表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2018-08-03
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多