如何在Rails 4 中设置嵌套资源控制器?

How to set up nested resources controller in Rails 4?

我的应用程序中有 3 个模型。用户(通过 Devise),post,然后回复。 用户可以是 post 和回复的父级,回复属于用户和 post。

出于某种原因,它不会将回复保存到数据库。在输出中我看不到 user_id。我用来创建 @reply 的函数是 current_user.replies.create(reply_params)。 html 输出大括号对我来说似乎有点奇怪。为什么 :comment in :replys 大括号?知道我做错了什么吗?

型号:

              class Post < ActiveRecord::Base
                belongs_to :user
                has_many :replies
                validates_presence_of :title, :tekst
                validates :tekst, length: {minimum: 10}
              end

              class User < ActiveRecord::Base
                devise :database_authenticatable, :registerable,
                :recoverable, :rememberable, :trackable, :validatable

                has_many :posts, dependent: :destroy
                has_many :replies

               end

            class Reply < ActiveRecord::Base
              belongs_to :post
              belongs_to :user
              validates_presence_of :user, :post, :comment
              validates :comment, length: {minimum: 10} 

             end

控制器:

       class RepliesController < ApplicationController
   before_action :set_post, only: [:new, :index, :create]
   before_filter :authenticate_user!
  def index
    @replies = @post.replies
  end

  def new
    @reply = Reply.new
  end

  def create
    @reply = current_user.replies.create(reply_params)

    respond_to do |format|
      if @reply.save
        format.html { redirect_to @post, notice: 'Reply was 
        successfully saved' }
        format.json { render json: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: 'Wrong entry' 
        }
    end
    end
  end

  private

  def reply_params
    params.require(:reply).permit(:comment, :post_id)
  end

  def set_post
    @post = Post.find(params[:post_id])
  end
end

表格:

<%= form_for [@post, @reply] do |f| %>
  <%= f.text_field :comment %>
  <% f.hidden_field :post_id, value: @post.id  %>
  <%= f.submit %>
<% end %>

架构:

  create_table "replies", force: :cascade do |t|
    t.integer  "post_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.text     "comment"
  end

  add_index "replies", ["post_id"], name: "index_replies_on_post_id"
  add_index "replies", ["user_id"], name: "index_replies_on_user_id"

以及它如何看待输出:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"lot of nubers",
"reply"=>{"comment"=>"sdfsddasd"}, "commit"=>"Create Reply", 
"post_id"=>"1"}

它失败了,因为您没有将 post 与回复相关联。试试这个...

def create
  @reply = @post.replies.new(reply_params)
  @reply.user = current_user

  respond_to do |format|
    if @reply.save
    ...
  end
end

此外,请注意您应该实例化回复(使用 new,而不是 create),然后保存它。