如何从多态表中制作表单?
我正在尝试创建一个评论,该评论可以评论其他评论,但全部来自单个帖子。
对我来说特别麻烦的是试图找出如何制作它,以便这一切都可以在后期展示中实现,而不是在编辑或新的中实现。这在结构上合理吗?
这样我就可以通过 Post.comments
或 Comment.comments
等或 Comments.parent
我的模型:
#comment.rb
belongs_to :post
belongs_to :parent, :class_name => 'Comment'
has_many :children, :class_name => 'Comment'
validates_presence_of :text
#post.rb
has_many :comments
accepts_nested_attributes_for :comments
posts_controller
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
routes.rb
resource :comments
我让我的评论表具有 :text
和 :post_id
属性。虽然我认为它不需要 :post_id
,但
我的表单应该是什么样子,应该在哪里?
这是我可怕的尝试:
- form_for @post do |f|
- f.fields_for :comments do |c|
= f.label 'Comments'
= f.text_area :text
= f.submit 'Submit'
但似乎没有必要这样做。
I am trying to create a comment that could comment on other comments but are all derived from a single post.
What is especially troubling for me is trying to figure out how to make it so that this can all be achieved in the post show and not its edit or new. Is this archtecturally reasonable?
That way I can access it via Post.comments
, or Comment.comments
etc. or Comments.parent
My Models:
#comment.rb
belongs_to :post
belongs_to :parent, :class_name => 'Comment'
has_many :children, :class_name => 'Comment'
validates_presence_of :text
#post.rb
has_many :comments
accepts_nested_attributes_for :comments
posts_controller
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
routes.rb
resource :comments
I made my comment table have a :text
and :post_id
attribute. Though I don't think it needs a :post_id
,
What should my form look like, where should it be?
Here's my awful attempt :
- form_for @post do |f|
- f.fields_for :comments do |c|
= f.label 'Comments'
= f.text_area :text
= f.submit 'Submit'
But it seems unecessary to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
完成此操作的两个关键组件是:
因为它在节目中,所以我需要指定此帖子的 URL:
但我很困惑,因为没有错误的地方,没有文本字段!
那是因为我的控制器没有提到这一点。所以我将其添加到
def show
Ta da,它现在可以工作了。
完整代码
控制器:
Two Key components to finishing this was this :
Because its in the show, I need to specify the URL to which this posts :
But I was confused because where there were no errors, there was no textfield!
That because my controller didn't mention one. So I added this to
def show
Ta da, it works now.
Full Code
Controller: