目前,我有一条属于微博的评论,但问题是,当用户创建评论时,注释会用微博id存储在数据库中,但id不是针对特定的微博,而是好像评论只是将微博id增加了+ 1。非常困惑,非常感谢任何帮助。谢谢!
注释模型
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id, :micropost_id
belongs_to :micropost
belongs_to :user
validates :content, presence: true, length: { maximum: 140 }
default_scope order: 'comments.created_at DESC'
end微柱模型
class Micropost < ActiveRecord::Base
attr_accessible :title, :content, :view_count
belongs_to :user
has_many :comments
accepts_nested_attributes_for :comments
end注释控制器
class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
format.html
format.js
end
end
end表单
<div class="CommentField">
<%= form_for ([@micropost, @micropost.comments.new]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>路由
resources :microposts do
resources :comments
end掠行路线
micropost_comments GET /microposts/:micropost_id/comments(.:format) comments#index
POST /microposts/:micropost_id/comments(.:format) comments#create
new_micropost_comment GET /microposts/:micropost_id/comments/new(.:format) comments#new
edit_micropost_comment GET /microposts/:micropost_id/comments/:id/edit(.:format) comments#edit
micropost_comment GET /microposts/:micropost_id/comments/:id(.:format) comments#show
PUT /microposts/:micropost_id/comments/:id(.:format) comments#update
DELETE /microposts/:micropost_id/comments/:id(.:format) comments#destroy发布于 2012-02-27 19:49:56
我认为这里的问题是你在这方面投入了多少精力。Rails的构建是为了了解其中的大部分内容,而不需要做您正在做的事情。我的建议是将您的评论控制器更改为这样的
class CommentsController < ApplicationController
def create
@comment = Comment.new(params[:comment])
@comment.save
respond_to do |format|
format.html
format.js
end
end
end由于您正在通过另一个分部呈现您的注释部分表单,因此您需要传递它上面关联的post的局部变量。
"comments/form", :locals => { :micropost => micropost } %> 你的身体就像这样
<div class="CommentField">
<%= form_for ([micropost, @comment]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>在我所有的rails应用程序中,这就是我需要做的所有关联,以使它能够自行正确地分配it。我相信这会解决问题的。
https://stackoverflow.com/questions/9469658
复制相似问题