2

そのため、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 %>
4

1 に答える 1

4

Your form is fine, except the first line (and you don't need a hidden field for the user_id, thats done through your relationship):

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

Should be:

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

Now you render a form for creating or updating a comment for a particular post.

However, you should change your model and controller.

class Post
  has_many :comments
end

class Comment
  belongs_to :post
end

This will give you access to @post.comments, showing all comments belonging to a particular post.

In your controller you can access comments for a specific post:

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

This way you can access the index of comments for a particular post.

Update

One more thing, your routes should also look like this:

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

This will give you access to post_comments_path (and many more routes)

于 2013-02-05T07:53:48.553 に答える