【问题标题】:rails form data not getting saved to dbrails表单数据没有保存到db
【发布时间】:2012-08-11 14:08:48
【问题描述】:

我是 Rails 新手,正在尝试制作一个简单的网站来开始学习。但是,当我提交表单时,数据不会保存到数据库中。我真的不知道出了什么问题,我一直在努力解决一段时间。如果我在 Rails 控制台中记录并保存它,该记录会成功显示在数据库中(以及索引页面上)。

计算.rb:

class Calculate < ActiveRecord::Base
  attr_accessible :number, :root
end

calculates_controller.rb:

class CalculatesController < ApplicationController
  def index
    @calculate = Calculate.all
  end

  def new
    @calculate = Calculate.new
  end

  def create
    @calculate = Calculate.new(params[:calculate])
    if @calculate.save
      redirect_to '/calculates'
    else
      render 'new'
      flash[:notice] = "Didn't work"
    end
  end
end

new.html.erb:

<%= form_for(@calculate) do %>
  <%= label_tag(:number, "Enter the number") %>
  <%= text_field_tag :number %>
  <%= label_tag(:root, "root") %>
  <%= text_field_tag :root %>
  <%= submit_tag("Submit") %>
<% end %>

【问题讨论】:

  • 我的 route.rb 中也有 resources :calculates

标签: ruby-on-rails ruby


【解决方案1】:

如果您使用的是form_for,请使用form_for syntax

<%= form_for(@calculate) do |form| %>
  <%= form.label :number %>
  <%= form.text_field :number %>
  <%= form.label :root %>
  <%= form.text_field :root %>
  <%= form.submit "Submit" %>
<% end %>

如果 @calculate 是新对象,它将自动处理路由,它将提交它以创建,或者如果它已经保存,它将向 edit action 发送一个 put 请求

【讨论】:

    【解决方案2】:

    啊哈!我将视图更新为:

    <%= form_for @calculate, :url => { :action => "create" } do |f| %>
      <%= f.label :number %>
        <%= f.text_field :number %>
        <%= f.label :root %>
        <%= f.text_field :root %>
        <%= submit_tag("Submit") %>
    <% end %>
    

    现在它可以工作了。太棒了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2020-11-09
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多