Rails形成输入字段而不保存到DB(但created_at时间戳是)

时间:2013-12-25 05:57:12

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

我是rails的新手,并试图理解为什么我的表单不会保存到数据库中。这可能是因为我没有完全掌握轨道的MVC框架,所以希望一旦我弄清楚它将提供清晰度。

更新时间保存,但其余记录显示为null。在我的提交按钮之外(触发更新和创建时间戳),数据库和我的表单之间似乎没有交互。

这是我的控制器:

  def create
  @recommendation=Recommendation.new
  end

这是我的表格:

<%= form_for @recommendation, url: {action: "create"} do |f| %>
    <% if @recommendation.errors.any? %>
    <div id="error_explanation">
    <h2><%= pluralize(@recommendation.errors.count, "error") %> prohibited this recommendation from being saved:</h2>
    <% end %> 

  <div><%= f.label "recommendation category"%><br />
  <%= f.text_field :rec_type %></div>

  <div><%= f.label "Description" %><br />
  <%= f.text_field :rec_description %></div>

  <div><%= f.label "Link" %><br />
  <%= f.text_field :link %></div>

  <div> <%= f.submit "Submit Recommendation" %></div>
<% end %>

提交后,这是我的日志:

Started POST "/recommendations/create" for 127.0.0.1 at 2013-12-25 00:42:39 -0500

Processing by RecommendationsController#create as HTML

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"U2+h08nRXgkkNp0u74a5Gmh0eSWU4gP67A2CWGaJ/fE=", "recommendation"=>{"rec_type"=>"asdf", "rec_description"=>"efads", "link"=>"wfea"}, "commit"=>"Submit Recommendation"}

   (0.1ms)  begin transaction

  SQL (617.6ms)  INSERT INTO "recommendations" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Wed, 25 Dec 2013 05:42:39 UTC +00:00], ["updated_at", Wed, 25 Dec 2013 05:42:39 UTC +00:00]]

   (1.6ms)  commit transaction

1 个答案:

答案 0 :(得分:0)

Model.new只是创建关联类的实例。它不会将其保存到数据库中。通过新操作渲染您的表单。你也没有在表单url中创建输出动作。根据rails约定,模型新实例总是转到其create方法。它应该是

def new
 @recommendation=Recommendation.new
end

def create
 @recommendation=Recommendation.new(allowed_params)
 @recommendation.save
end

private
def allowed_params
  params.require(:recommendation).permit(:rec_type, :rec_description, :link)
end