【问题标题】:rails: mass-assign error caused by updating child (Post) from parent (Topic) controller (edit view)rails:从父(主题)控制器更新子(帖子)导致的批量分配错误(编辑视图)
【发布时间】: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


    【解决方案1】:

    在更新方法中,您不必更新两个模型的属性,而不是 if @topic.update_attributes(params[:topic]) &amp;&amp; post.update_attributes(params[:post]) 它应该只有 if @topic.update_attributes(params[:topic]) 它会自动更新帖子。

    并将您的视图从 &lt;%= f.fields_for @topic.posts.first do |post| %&gt; 更改为 &lt;%= f.fields_for :posts, @topic.posts.first do |post| %&gt; 它将正常工作。

    更多信息请阅读http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

    【讨论】:

    • &lt;%= f.fields_for :posts, @topic.posts.first do |post| %&gt; 这是一个很棒的技巧。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多