【发布时间】:2012-06-14 06:13:00
【问题描述】:
我正在尝试编辑包含许多帖子的主题。
主题的编辑页面具有可以编辑的主题name 和帖子content。
在topics_controller.rb,update方法,post.update_attributes(params[:post])中出现批量赋值错误。
如何避免批量分配错误。
topic.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
topics_controller.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
views/topics/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 %>
views/posts/_form.html.erb
<%= f.label :content %>
<%= f.text_area :content %>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 nested-forms mass-assignment