0

i've a rails 4 instance running with a pages model which has different types of page contents like PageContent::Text which inherits from PageContent.

in my form i render all my @page.page_contents as you can see in the form snippet..

if i update my page the records doesnt get updated they are created as new records.

# update controller
class Admin::PagesController < Admin::BaseController

  def update
    @page = Page.find_by_url(params[:id])

    respond_to do |format|
      if @page.update_attributes(page_params(@page.type.parameterize.gsub('page','')))
        format.html { redirect_to edit_admin_page_path(@page) }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  def page_params(type)
    params.require("#{type}_page".to_sym).permit(:name, :contents_attributes => [:body, :type])
  end

end

# content model
class PageContent::Text < PageContent
end

# page model
class Page < ActiveRecord::Base
  has_many :contents, class_name: 'PageContent', dependent: :destroy
  accepts_nested_attributes_for :contents
end

# form snippet
<textarea class="form-control wysihtml5" id="content_page_contents_attributes_0_body" name="content_page[contents_attributes][0][body]">
testsetseet</textarea>
<input id="content_page_contents_attributes_0_type" name="content_page[contents_attributes][0][type]" type="hidden" value="PageContent::Text" />
<input id="content_page_contents_attributes_0_id" name="content_page[contents_attributes][0][id]" type="hidden" value="1" />

any ideas would be very welcome!

thanks in advance

Oliver
  • 801
  • 13
  • 26
  • 1
    Maybe just adding `:id` to `.permit(:name, :contents_attributes => [:body, :type])` will solve the problem? like `:contents_attributes => [:body, :type, :id]`. Also have a look on server stdout - it outputs which attributes are not permitted – roman-roman Oct 23 '13 at 09:01
  • yeah adding id to permitted attributes solved the problem!! awesome thanks! – Oliver Oct 23 '13 at 10:20
  • I post it as an answer so you can accept it. Thanks. – roman-roman Oct 23 '13 at 12:04

1 Answers1

5

Maybe just adding :id to .permit(:name, :contents_attributes => [:body, :type])will solve the problem?

The result should look like :contents_attributes => [:body, :type, :id].

Also have a look on server stdout - it outputs which attributes are not permitted.

roman-roman
  • 2,746
  • 19
  • 27
  • 2
    This answer helped me on a problem I have been working on for days! Thanks a ton. I have a question though - is it secure to permit the user to change the id? – Philip7899 Nov 05 '13 at 16:20
  • Unfortunately `:id` is not marked as not permitted. It just creates a new record until you add `:id` to the permitted attributes and the nested record can be updated at last. Many thanks. – gemp Aug 14 '20 at 13:58