我有兩個資源:主題和帖子。 我想弄清楚如何通過Post控件創建主題。 這些模型是這樣的:如何通過rails 3中的子控制器創建父模型? (belongs_to association)
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 %>
posts_controller.rb#創建:
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
隨着職位/ _form.html.erb我可以創建帖子,但不會隨之創建相關主題。任何人都可以告訴我爲什麼我會得到這種行爲,並可能如何糾正?我使用Ruby 1.9.2,Rails 3.0.7和simple_form gem。
這個工作!我正在計劃實現該領域的自動完成,並知道選擇框的方法。非常適合你的時間。 – BasicObject 2011-05-01 23:07:32