gpt4 book ai didi

ruby-on-rails - Ruby on Rails 协会表格

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:16 25 4
gpt4 key购买 nike

所以我正在使用 ROR 制作一个网络应用程序,但我无法弄清楚这种形式的正确语法是什么。我目前正在为评论和帖子制作关联类型的代码。

<%= form_for @comment do |f| %>
<p>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</p>

<p>
<%= f.submit "Add Comment" %>
</p>
<% end %>

最佳答案

你的表单很好,除了第一行(你不需要 user_id 的隐藏字段,这是通过你的关系完成的):

<%= form_for(@comment) do |f| %>

应该是:

<%= form_for([@post, @comment]) do |f| %>

现在您呈现一个表单,用于创建或更新特定帖子的评论。

但是,您应该更改模型和 Controller 。

class Post
has_many :comments
end

class Comment
belongs_to :post
end

这将使您能够访问@post.comments,显示属于特定帖子的所有评论。

在您的 Controller 中,您可以访问特定帖子的评论:

class CommentsController < ApplicationController
def index
@post = Post.find(params[:post_id])
@comment = @post.comments.all
end
end

这样您就可以访问特定帖子的评论索引。

更新

还有一件事,你的路线也应该是这样的:

AppName::Application.routes.draw do
resources :posts do
resources :comments
end
end

这将使您能够访问 post_comments_path(以及更多路由)

关于ruby-on-rails - Ruby on Rails 协会表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14702459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com