模型ID在创建评论时不保存。如何正确保存?

时间:2014-01-08 13:22:59

标签: ruby-on-rails ruby

我已经设置了三个模型。用户,指南和评论。用户有许多指南和评论。指南属于用户并且有许多注释。评论属于用户和指南。

当我在控制台中运行Comment.last.user时,它会返回与用户相关的信息。但是,当我在控制台中运行Comment.last.guide时,它会返回nil。创建评论时出现了问题。

这些模型都设置了经典的has_manybelongs_to关系,所以我将省略这些。这是评论控制器:

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]

  # GET /comments
  # GET /comments.json
  def index
    @comments = Comment.all
  end

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

  # GET /comments/new
  def new
    @comment = Comment.new
  end

  # GET /comments/1/edit
  def edit
  end

  # POST /comments
  # POST /comments.json
  def create
    @comment = current_user.comments.build(comment_params)


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

  # PATCH/PUT /comments/1
  # PATCH/PUT /comments/1.json
  def update
    respond_to do |format|
      if @comment.update(comment_params)
        format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to comments_url }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:body, :user_id, :guide_id)
    end
end

以下是评论迁移:

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body
      t.references :user, index: true
      t.references :guide, index: true

      t.timestamps
    end
  end
end

创建评论时记录输出:

Started POST "/comments" for 127.0.0.1 at 2014-01-08 08:30:54 -0500
Processing by CommentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"D2BvBIgU+tniZvr2NgQE/TpHY6J2xHOUm701jqTcJ9A=", "comment"=>{"body"=>"NitinJ Sample Comment", "user_id"=>"some value", "guide_id"=>"some value"}, "commit"=>"Create Comment"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (21.7ms)  INSERT INTO "comments" ("body", "created_at", "guide_id", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?)  [["body", "NitinJ Sample Comment"], ["created_at", Wed, 08 Jan 2014 13:30:54 UTC +00:00], ["guide_id", 0], ["updated_at", Wed, 08 Jan 2014 13:30:54 UTC +00:00], ["user_id", 1]]
   (21.0ms)  commit transaction
Redirected to http://localhost:3000/guides/1-attack
Completed 302 Found in 53ms (ActiveRecord: 43.1ms)


Started GET "/guides/1-attack" for 127.0.0.1 at 2014-01-08 08:30:54 -0500
Processing by GuidesController#show as HTML
  Parameters: {"id"=>"1-attack"}
  Guide Load (0.2ms)  SELECT "guides".* FROM "guides" WHERE "guides"."id" = ? LIMIT 1  [["id", "1-attack"]]
  CACHE (0.0ms)  SELECT "guides".* FROM "guides" WHERE "guides"."id" = ? LIMIT 1  [["id", "1-attack"]]
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."guide_id" = ?  [["guide_id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
  Rendered comments/_form.html.erb (6.6ms)
  Rendered guides/show.html.erb within layouts/application (18.9ms)
DEPRECATION WARNING: Calling #sum with a block is deprecated and will be removed in Rails 4.1. If you want to perform sum calculation over the array of elements, use `to_a.sum(&block)`. (called from _app_views_layouts__navbar_html_erb__2351226726967046587_2202447400 at /Users/DylanRichards/Desktop/runescapeguides/app/views/layouts/_navbar.html.erb:35)
  Guide Load (0.2ms)  SELECT "guides".* FROM "guides" WHERE "guides"."user_id" = ?  [["user_id", 1]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 1], ["votable_type", "Guide"]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 1], ["votable_type", "Guide"]]
  Rendered layouts/_navbar.html.erb (7.4ms)
Completed 200 OK in 54ms (Views: 47.8ms | ActiveRecord: 1.5ms)

第二次日志输出

Started POST "/guides/1-attack/comments" for 127.0.0.1 at 2014-01-08 08:52:29 -0500
Processing by CommentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"D2BvBIgU+tniZvr2NgQE/TpHY6J2xHOUm701jqTcJ9A=", "comment"=>{"body"=>"Another sample NitinJ comment.", "user_id"=>"some value", "guide_id"=>"some value"}, "commit"=>"Create Comment", "guide_id"=>"1-attack"}
Completed 500 Internal Server Error in 69ms

NoMethodError (undefined method `[]=' for nil:NilClass):
  app/controllers/comments_controller.rb:27:in `create'


  Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
  Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.7ms)
  Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.5ms)
  Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (21.7ms)

1 个答案:

答案 0 :(得分:1)

试试这个<%= f.association :guide, :as => :hidden, :input_html => { :value => @guide.id }%>

相关问题