我正在使用我们使用rails教程构建的注册和登录作为我正在制作的Reddit克隆的基础。目前应用程序运行正常,除了评论表中的user_id是空白的,当我发表评论时,link_id存在并且正确,所以我可以对链接发表评论。链接表中的user_id也存在且正确。
我很确定我所犯的错误是在comments_controller.rb的创建操作中,但它也可能是我原来的迁移。令我困惑的是(作为一个新手)我曾经使用rails 4.1.8和设备之前使用过它的当前形式。但是,使用rails 4.2.1这种方法使用rails教程作为基础,它不起作用。我在这里有点新意,所以我希望我已经正确地制定了这个帖子并提供了足够的信息,所以有人可以给我一些关于问题的指示
评论控制器
before_action :logged_in_user, only: [:create, :destroy]
def create
@link = Link.find(params[:link_id])
@comment = @link.comments.create(params[:comment].permit(:link_id, :body))
@comment.user = User.find(current_user.id)
redirect_to link_path(@link)
end
def destroy
@link = Link.find(params[:link_id])
@comment = @link.comments.find(params[:id])
@comment.destroy
redirect_to link_path(@link)
end
private
def logged_in_user
unless logged_in?
flash[:danger] = "Please log in."
redirect_to login_url
end
end
表格 应用程序/视图/链接/ show.html.erb
<h2 class="comment-count"><%= pluralize(@link.comments.count, "comment") %></h2>
<%= render @link.comments %>
<%= form_for([@link, @link.comments.build]) do |f| %>
<%= render 'comments/fields', f: f %>
<%= f.submit "Save Comment", class: 'btn btn-primary margin-bottom-10' %>
<% end %>
局部模板 应用程序/视图/评论/ _comment.html.erb
<p class="comment_body"><%= comment.body %></p>
<p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago </p>
应用程序/视图/评论/ _fields.html.erb
<%= render 'shared/comment_error_messages' %>
<%= f.label :body %>
<%= f.text_area :body, class: 'form-control' %>
路线 配置/ routes.rb中
resources :links do
member do
put "like", to: "links#upvote"
put "dislike", to: "links#downvote"
end
resources :comments
end
模型 应用程序/模型/ link.rb
belongs_to :user
has_many :comments, dependent: :destroy
应用程序/模型/ comment.rb
belongs_to :user
belongs_to :link
validates :body, presence: true
应用程序/模型/ user.rb
has_many :links, dependent: :destroy
移植
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.integer :link_id
t.text :body
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
add_index :comments, :link_id
end
end
希望这是一个足够好的帖子,我已经包含了你需要的一切,所以有人可以帮助我,这是一个菜鸟错误,但我看不到它。提前谢谢。
此致
答案 0 :(得分:1)
目前,您正在创建comment
而不保存user_id
。请尝试以下代码
#comments_controller.rb
def create
@link = Link.find(params[:link_id])
@comment = @link.comments.new(params[:comment].permit(:link_id, :body))
@comment.user = User.find(current_user.id)
@comment.save
redirect_to link_path(@link)
end