在RoR标准MVC CRUD操作中未将表单字段保存到数据库

时间:2014-05-05 23:18:23

标签: ruby-on-rails

我正在使用Rails 4.1.0

我的观点:

<%= form_for @book do |f| %>

    <%= f.text_field :title %>
    <%= f.text_field :author %>
    <%= f.number_field :pages %>
    <%= f.text_field :description %>
    <%= f.submit "Add book" %>
<% end %>

我的控制器:

class BooksController < ApplicationController
  def new
    @book = Book.new
  end
  def create
    @book = Book.new(book_params)
    if @book.save
        redirect_to '/', notice: "You have succesfully added a book"
    else
        flash.now[:error] = "Something went wrong"
        render :new
    end
  end

  private
  def book_params
    params.require(:book).permit(:title, :author, :pages, :description)
  end
end

我的模特:

class Book < ActiveRecord::Base

    validates :title, presence: true
    validates :title, uniqueness: true

    attr_accessor :title, :author, :pages, :description
end

基本CRUD,但是当我尝试保存到数据库时,只创建一个空记录,这反映在开发日志中:

Started POST "/books" for 10.0.2.2 at 2014-05-05 22:59:08 +0000
Processing by BooksController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SDB/oB/CjZsBHmI0zLPmQnKpZSxO7piGnsLSzEy2hyA=", "book"=>{"title"=>"tittel", "author"=>"te", "pages"=>"", "description"=>""}, "commit"=>"Add book"}
  [1m[36m (0.2ms)[0m  [1mbegin transaction[0m
  [1m[35mBook Exists (3.9ms)[0m  SELECT  1 AS one FROM "books"  WHERE "books"."title" = 'tittel' LIMIT 1
  [1m[36mSQL (5.0ms)[0m  [1mINSERT INTO "books" ("created_at", "updated_at") VALUES (?, ?)[0m  [["created_at", "2014-05-05 22:59:08.989197"], ["updated_at", "2014-05-05 22:59:08.989197"]]
  [1m[35m (5.9ms)[0m  commit transaction
Redirected to http://localhost:3003/
Completed 302 Found in 26ms (ActiveRecord: 15.0ms)

我在这里缺少什么?提前谢谢!

1 个答案:

答案 0 :(得分:3)

我认为你在这里混淆了两个重叠的概念:

仅允许某些参数创建数据库记录的旧(ish)方法是将它们列入白名单,我认为这是您使用attr_accessor尝试的内容,但正确的方法是attr_accessible

控制params可以创建数据库记录的新方法是strong params模式,您使用私有book_params方法实现了该模式。但是,如果你正在做强大的障碍,你不需要进行白名单。

因此,如果您只是完全取出attr_accessor位,那应该可以解决问题。