错误:param丢失或值为空:事情

时间:2014-09-27 23:12:03

标签: ruby-on-rails ruby-on-rails-4 controller params actioncontroller

我使用的是rails 4.0.8。我在一个名为' Things'的模型中添加了一个评论部分,但我一直得到同样的错误" param丢失或者值为空:事情"当我按下提交评论按钮。它说错误发生在Things#Controller中。我做错了什么?

更新:我从表单中删除了url路径,但是一个新的错误返回"找不到没有ID"的东西。错误发生在评论#Controller。

查看/显示

<div id= "thing">
  <h1>
    <%= @thing.name %>
  </h1>
  <br>
  <div id= "commentsection">
    Comments
    <div id= "comments">
      <br>
      <% @thing.comments.each do |c| %>
        <%= c.username %>
        <br>
        <%= c.text %>
      <% end %>
      <%= form_for @comment, :url => thing_path do |f| %>

        <%= f.label :username %>
        <%= f.text_field :username %>

        <%= f.label :comment %>
        <%= f.text_field :text %>

        <%= f.submit "Enter", class: "btn btn-small btn-primary" %>
      <% end %>
    </div>
  </div>
</div>

善于控制者

class ThingsController < ApplicationController

  def show
    @thing = Thing.find(params[:id])
    @thing.comments.build
    @comment = Comment.new
  end

  def index
  end

  def new
    @thing = Thing.new
    @things = Thing.all
  end

  def create
    @thing = Thing.new(thing_params)
    if @thing.save
      redirect_to @thing
    else
      render 'new'
    end
  end

  private
    def thing_params
      params.require(:thing).permit(:name, :avatar)
    end

end

COMMENTS CONTROLLER(我把星号放在错误所在的行周围)

class CommentsController < ApplicationController

  def show
    @comment = Comment.find(params[:id])
  end

  def new
    @comment = Comment.new
    @comments = Comment.all
  end

  def create
    ****@thing = Thing.find(params[:thing_id])****
    @comment = @thing.comments.create(comment_params)
    redirect_to thing_path(@thing)
    end
  end

  private

    def comment_params
      params.require(:comment).permit(:user, :text, :upvotes, :downvotes, :thing_id)
    end

end

路线

Website::Application.routes.draw do

  get "comments/new"
  get "comments/show"
  get "things/new"
  root 'home_page#home'
  get "all/things/new" => 'things#new'
  get "all/allthings"
  resources :things
    resources :good_comments
  get "things/show"
  get "things/results"

end

1 个答案:

答案 0 :(得分:0)

您要将@comment表单发布到post '/things' path

<%= form_for @comment, :url => thing_path do |f| %>

它应该只是<%= form_for @comment do %>(Rails足够聪明,可以插入comments_path)或者你觉得更明确(即使没有必要)

<%= form_for @comment, url: :comments_path do %>

另一个注意事项是,如果您希望Comment与特定Thing相关联,那么在您的模型中它应该是

Class Thing
  has_many :comments
end

Class Comment
  belongs_to :thing
end

然后确保您的数据库comment中有thing_id foreign_key field,然后您的评论表单实际上应该是

<%= form_for @thing, @comment do %> <% end %>