如何在Rails中创建多模型,多页面的表单?

时间:2011-09-25 03:10:55

标签: ruby-on-rails forms has-many

我是一个尝试学习Ruby on Rails的新手。我正在尝试学习如何使用has_many关联。我有一个博客,我希望能够添加评论。我可以在帖子页面中添加评论表单,但我还想通过转到带有“添加评论表单”的新页面来学习如何添加评论。

但是,我无法传递评论所属帖子的必要信息。我不确定我的表单或comments_controller是否有问题。

posts_controller

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
  end
  def new
    @post = Post.new
  end
  def index
    @posts = Post.all
  end
end

comments_controller

class CommentsController < ApplicationController
  def new
    @comment = Comment.new  
  end
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

评论模型

class Comment < ActiveRecord::Base
  belongs_to :post
end

发布模型

class Post < ActiveRecord::Base
  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  has_many :comments, :dependent => :destroy
  accepts_nested_attributes_for :comments
end

评论表

    <h1>Add a new comment</h1>
    <%= form_for @comment do |f| %>
      <div class="field">
        <%= f.label :commenter %><br />
        <%= f.text_field :commenter %>
      </div>
      <div class="field">
        <%= f.label :body %><br />
        <%= f.text_area :body %>
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

routes.rb

Blog::Application.routes.draw do
  resources :posts do
    resources :comments
  end
  resources :comments
  root :to => "home#index"
end

1 个答案:

答案 0 :(得分:0)

我猜您需要在评论页面中添加帖子ID。

做这样的事情:

当您重定向到评论控制器时,传递帖子ID并从评论控制器

获取
class CommentsController < ApplicationController
  def new
    @post_id = params[:id] 
    @comment = Comment.new  
  end
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

在您的comments / new.erb视图中,将帖子ID添加为隐藏的参数

<h1>Add a new comment</h1>
<%= form_for @comment do |f| %>
  <div class="field">
    <%= f.label :commenter %><br />
    <%= f.text_field :commenter %>
  </div>
  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %><%= f.text_field :post_id, @post_id  %>
  </div>
<% end %>