我有两个资源:主题和帖子。我试图弄清楚如何通过 Post 控制器创建主题。模型如下所示:
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
validates :name, :presence => true,
:length => { :maximum => 32 }
attr_accessible :name
end
class Post < ActiveRecord::Base
belongs_to :topic, :touch => true
has_many :comments, :dependent => :destroy
accepts_nested_attributes_for :topic
attr_accessible :name, :title, :content, :topic
end
帖子/_form.html.erb:
<%= simple_form_for @post do |f| %>
<h1>Create a Post</h1>
<%= f.input :name, :label => false, :placeholder => "Name" %>
<%= f.input :title, :label => false, :placeholder => "Title" %>
<%= f.input :content, :label => false, :placeholder => "Content" %>
<%= f.input :topic, :label => false, :placeholder => "Topic" %>
<%= f.button :submit, "Post" %>
<% end %>
post_controller.rb#create:
def create
@post = Post.new(params[:topic])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
使用 posts/_form.html.erb 我可以创建帖子,但不会随之创建相关主题。谁能告诉我为什么我会出现这种行为以及如何纠正它?我正在使用 Ruby 1.9.2、Rails 3.0.7 和 simple_form gem。