我正在尝试编辑一个有很多帖子的主题。主题的编辑页面具有可以编辑的主题name
和帖子。content
批量分配错误发生在 topic_controller.rb, update
method, 中post.update_attributes(params[:post])
。
如何避免批量分配错误。
主题.rb
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
belongs_to :forum
accepts_nested_attributes_for :posts, :allow_destroy => true
attr_accessible :name, :last_post_id, :posts_attributes
end
post.rb
class Post < ActiveRecord::Base
belongs_to :topic
attr_accessible :content
end
主题控制器.rb
def update
@topic = Topic.find(params[:id])
post = @topic.posts.first
if @topic.update_attributes(params[:topic]) && post.update_attributes(params[:post])
topic = Topic.find(@post.topic_id)
flash[:success] = "Success!"
redirect_to topic_posts_path(topic)
else
render 'edit'
end
end
意见/主题/edit.html.erb
<%= form_for @topic do |f| %>
<!-- render 'shared/error_messages_topic' -->
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for @topic.posts.first do |post| %>
<%= render :partial => "posts/form", :locals => {:f => post} %>
<% end %>
<%= f.submit "Edit", class: "btn btn-large btn-primary" %>
<% end %>
意见/帖子/_form.html.erb
<%= f.label :content %>
<%= f.text_area :content %>