【问题标题】:Active Record belongs_to association not adding foreign keyActive Record belongs_to 关联不添加外键
【发布时间】:2015-04-04 22:45:49
【问题描述】:

我有一个嵌套资源,其中包含许多“cmets”的“posts”以及在这些模型之间建立的关联。但是,当我为帖子创建评论时,cmets 表中的“post_id”仍然为空,并且没有建立链接。评论文本本身创建正常。

我使用的是 Rails 4.2.1 版和一个 postgresql 数据库。

关联设置如下:

class Comment < ActiveRecord::Base
  belongs_to :post
end

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy
end

这是设置的路线:

资源:帖子做 资源:cmets 结束

我使用以下代码从 cmets/new 视图创建 cmets:

= form_for [@post, @comment] do |f|
  = f.label :comment
  = f.text_field :comment
  = f.submit "Add Comment"

我的 cmets 控制器是这样的:

class CommentsController < ApplicationController

  def new
    @post = Post.find(params[:post_id])
    @comment = Comment.new
  end

  def create
    @post = Post.find(params[:post_id])
    @comment = Comment.create(comment_params)
    redirect_to posts_path
  end

  def comment_params
    params.require(:comment).permit(:comment)
  end

end

我在 cmets 表中设置了“post_id”列,我的架构是这样的:

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

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "comments", force: :cascade do |t|
    t.string   "comment"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "post_id"
  end

  add_index "comments", ["post_id"], name: "index_comments_on_post_id", using: :btree

  create_table "posts", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_foreign_key "comments", "posts"
end

只是无法弄清楚发生了什么,我在另一个项目中使用了几乎相同的代码并且有效。

任何帮助都会很棒。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord associations


    【解决方案1】:

    在这段代码中:

     def create
        @post = Post.find(params[:post_id])
        @comment = Comment.create(comment_params)
        redirect_to posts_path
     end
    

    您找到了该帖子,但从未对其进行任何操作。该评论对该帖子一无所知。您需要将评论的帖子设置为@post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      相关资源
      最近更新 更多