嵌套模型不会更新

时间:2014-08-03 12:33:32

标签: ruby-on-rails ruby-on-rails-4 nested-attributes

我有两个模型:PointPagePointPageClassbelongs_to :point_page。当用户创建PointPage rails时,会在数据库中创建多个(现在有#6;其中6个)PointPageClasses。我需要在PointPage edit页面上修改所有这些内容。所以,我在控制器中使用嵌套属性,在视图中使用fields_for

point_page_form

<%= form_for @point_page, role: 'form' do |f| %>
    <div class="form-group">
      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>
    </div>

    ... # some other PointPage fields

    <% @point_page.point_page_classes.each do |class| %>
        <%= f.fields_for :point_page_classes do |builder| %>
            <div class="row">
              <div class="col-lg-6">
                  <%= builder.text_field :distance_price, class: 'form-control' %>
              </div>
              <div class="col-lg-6">
                  <%= builder.text_field :show_price, class: 'form-control' %>
              </div>
            </div>
        <% end %>
    <% end %>

    <%= f.submit 'Save', class: 'btn btn-default' %>
<% end %>

point_page_controller

def update
    @point_page = PointPage.find(params[:id])
    if @point_page.update_attributes(point_page_params)
      respond_to do |format|
        format.html { redirect_to new_point_path }
        format.js
      end
    end
end

private

def point_page_params
  params.require(:point_page).permit(:name, :url, :article,
             point_page_classes_attributes: [:distance_price, :show_price])
end

所以,我已添加point_page_controller PointPageClass个属性,但是当我保存更改时,它只保存PointPage的更改,但不保存PointPageClass的更改(distance_priceshow_price)。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

其中一个问题可能是:id中不允许point_page_params。要update发生,您需要允许:id

尝试将point_page_params更改为喜欢此内容

def point_page_params
  params.require(:point_page).permit(:id,:name, :url, :article,point_page_classes_attributes: [:id,:distance_price, :show_price])
end