Ruby on Rails的交往形式(Ruby on Rails Association Form)

2019-07-19 06:49发布

所以我使用ROR提出一个web应用程序,我想不通这种形式正确的语法是什么。 我目前正在做的代码的文章和评论的关联类型。

<%= 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 %>

Answer 1:

您的形式是很好,除了第一行(你不需要隐藏字段为USER_ID,通过你的关系做了多数民众赞成):

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

应该:

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

现在你渲染创建或更新的特定讯息的评论的形式。

但是,你应该改变你的模型和控制器。

class Post
  has_many :comments
end

class Comment
  belongs_to :post
end

这将让您使用@ post.comments,呈现出属于特定职位的所有评论。

在你的控制器,你可以为特定的访问后评论:

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 Association Form