【发布时间】:2011-09-25 03:10:55
【问题描述】:
我是一个尝试学习 Ruby on Rails 的新手。我正在尝试学习如何使用 has_many 关联。我有一个我希望能够添加 cmets 的博客。我可以在帖子页面中添加一个添加 cmets 表单,但我还想通过“添加 cmets 表单”转到一个新页面来了解如何添加 cmets。
但是,我无法传递有关评论所属帖子的必要信息。我不确定这是我的表单还是 cmets_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
cmets_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
【问题讨论】:
标签: ruby-on-rails forms has-many