[英]The Create method in a Comments controller is not working. Rails
我知道针对该主题也曾提出过类似的问题,但我已经阅读了所有这些问题,因此无法找到明确的解决方案。 在陈述问题之前,我将发布所有必需的代码。
型号:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :scoreboard
end
class User < ActiveRecord::Base
has_many :scoreboards, dependent: :destroy
has_many :comments, dependent: :destroy
end
class Scoreboard < ActiveRecord::Base
belongs_to :user
has_many :teams, dependent: :destroy
has_many :comments, dependent: :destroy
end
记分板类似于文章页面,用户可以在其中发表评论。
评论的迁移:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.text :reply
t.references :user, index: true
t.references :scoreboard, index: true
t.timestamps null: false
end
add_foreign_key :comments, :users
add_foreign_key :comments, :scoreboards
end
end
问题在于注释控制器中的create方法。 这是该方法的代码:
def create
@scoreboard = Scoreboard.find(params[:scoreboard_id])
@comment.user_id = current_user.id
@comment = @scoreboard.comments.build(comment_params)
redirect_to scoreboard_url(@comment.scoreboard_id)
end
current_user方法位于单独文件夹中的帮助文件中。 每当我提交表单以发表新评论时,都会出现以下错误:
undefined method `user_id=' for nil:NilClass
堆栈上的一个问题表明,注释中需要一个user_id列,而当我尝试迁移它时,则无法创建重复的列。 是否因为迁移中已经存在用户的外键? 我可能做错了什么?
错误非常简单:
@comment.user_id = current_user.id
@comment = @scoreboard.comments.build(comment_params)
您正在调用@comment
而不预先定义它。
应该是这样的:
@comment = @scoreboard.comments.build comment_params
@comment.user_id = current_user.id
堆栈中的一个问题表明注释中需要一个user_id列
为了澄清起见,他们指的是Comment
模型的foreign_key
。
您必须记住,Rails是建立在关系数据库之上的:
无论您使用哪种SQL变体,您仍将以关系方式使用它。 Rails已向其中添加ActiveRecord“对象关系映射器” 。
简而言之,这使Rails能够通过不同的查询等调用关联数据。 仅@scoreboard.comments
关联。
在后端,Rails必须计算哪些数据与另一个相关。 这仅在使用适当的关系数据库结构(包括使用foreign_keys
。
这就是创建关联对象时必须分配诸如user_id
。 但是,有一个技巧可以使它更加简洁:
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@scoreboard = Scoreboard.find params[:scoreboard_id]
@comment = @scoreboard.comments.build comment_params
end
private
def comment_params
params.require(:comment).permit(:params).merge(user_id: current_user.id)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.