输入字段在Rails数据库中显示nil

时间:2014-08-12 00:25:05

标签: ruby-on-rails ruby

我创建了一个食谱支架,允许用户创建许多食谱。我将user_id与控制器中的cookbook相关联,但标题和描述在rails数据库中显示为nil。

    class CookBooksController < ApplicationController
  before_action :set_cook_book, only: [:show, :edit, :update, :destroy]


  # GET /cook_books
  # GET /cook_books.json
  def index
    @cook_books = CookBook.all
  end

  # GET /cook_books/1
  # GET /cook_books/1.json
  def show
  end

  # GET /cook_books/new
  def new
    @cook_book = CookBook.new()
  end

  # GET /cook_books/1/edit
  def edit
  end

  # POST /cook_books
  # POST /cook_books.json
  def create
    @cook_book = CookBook.new(cook_book_params)
    @cook_book.user_id = current_user.id  


    respond_to do |format|
      if @cook_book.save
        format.html { redirect_to @cook_book, notice: 'Cook book was successfully created.' }
        format.json { render :show, status: :created, location: @cook_book }
      else
        format.html { render :new }
        format.json { render json: @cook_book.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /cook_books/1
  # PATCH/PUT /cook_books/1.json
  def update
    respond_to do |format|
      if @cook_book.update(cook_book_params)
        format.html { redirect_to @cook_book, notice: 'Cook book was successfully updated.' }
        format.json { render :show, status: :ok, location: @cook_book }
      else
        format.html { render :edit }
        format.json { render json: @cook_book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /cook_books/1
  # DELETE /cook_books/1.json
  def destroy
    @cook_book.destroy
    respond_to do |format|
      format.html { redirect_to cook_books_url, notice: 'Cook book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_cook_book
      @cook_book = CookBook.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def cook_book_params
      params.require(:cook_book).permit(:title, :user_id, :description)
    end
end




class CookBook < ActiveRecord::Base
    belongs_to :users 
end




ActiveRecord::Schema.define(version: 20140811235307) do

  create_table "cook_books", force: true do |t|
    t.string   "title"
    t.integer  "user_id"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "pages", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "header"
  end

  create_table "users", force: true do |t|
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "username"
    t.string   "country"
    t.string   "address"
    t.string   "provider"
    t.string   "uid"
    t.boolean  "admin",                  default: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

任何帮助都欣赏它!谢谢

EDIT!表格已添加

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

      <ul>
      <% @cook_book.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_field :description %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

EDIT!服务器日志

Started GET "/cook_books/new" for 127.0.0.1 at 2014-08-12 02:21:05 -0400
  ActiveRecord::SchemaMigration Load (0.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by CookBooksController#new as HTML
  Rendered cook_books/_form.html.erb (30.2ms)
  Rendered cook_books/new.html.erb within layouts/application (36.9ms)
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
  Rendered layouts/_header.html.erb (28.2ms)
Completed 200 OK in 335ms (Views: 306.3ms | ActiveRecord: 1.7ms)



Started POST "/cook_books" for 127.0.0.1 at 2014-08-12 02:21:15 -0400
Processing by CookBooksController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"TNDketl0ixC8Lh/aAWIGf7SWeiwHZR9ITlEEpa7/+xM=", "cook_book"=>{"title"=>"Test title", "description"=>"test description "}, "commit"=>"Create Cookbook"}
**WARNING: Can't mass-assign protected attributes for CookBook: title, description
    app/controllers/cook_books_controller.rb:28:in `create'** (Just saw this)
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.9ms)  INSERT INTO "cook_books" ("created_at", "updated_at", "user_id") VALUES (?, ?, ?)  [["created_at", "2014-08-12 06:21:15.547634"], ["updated_at", "2014-08-12 06:21:15.547634"], ["user_id", 1]]
   (1.4ms)  commit transaction
Redirected to http://localhost:3000/cook_books/8
Completed 302 Found in 29ms (ActiveRecord: 2.9ms)


Started GET "/cook_books/8" for 127.0.0.1 at 2014-08-12 02:21:15 -0400
Processing by CookBooksController#show as HTML
  Parameters: {"id"=>"8"}
  CookBook Load (0.4ms)  SELECT  "cook_books".* FROM "cook_books"  WHERE "cook_books"."id" = ? LIMIT 1  [["id", 8]]
  Rendered cook_books/show.html.erb within layouts/application (1.4ms)
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
  Rendered layouts/_header.html.erb (2.3ms)
Completed 200 OK in 34ms (Views: 30.9ms | ActiveRecord: 0.7ms

EDIT!型号

class CookBook < ActiveRecord::Base
    belongs_to :users 
end

1 个答案:

答案 0 :(得分:1)

您的代码很好,但是当查看server log时,您会收到此警告

  

无法为CookBook大量分配受保护的属性:title,   描述

根据评论,确认您拥有此宝石protected_attributes。这会添加默认attr_accessible。但是当它带有Rails4时,此宝石不是必需的。您可以使用此宝石。需要删除它以使事情有效。

小记:

正如 @Jaugar Chang 指出的那样,你有belongs_to :users。它应该是belongs_to :user。这会导致更多问题。