Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails accepts_nested_attributes_for always creates the nested models, but does not update them

Given the following:

class WebsitesController < ApplicationController
  # POST /websites/save
  # POST /websites/save.json
  def save
    Website.exists?(name: params[:website][:name]) ? update : create
  end

  # POST /websites
  # POST /websites.json
  def create
    @server  = Server.find_or_create_by_name(params[:server_id])
    @website = @server.websites.new(params[:website])

    #etc... @website.save
  end

  # PUT /websites/1
  # PUT /websites/1.json
  def update
    @website = Website.find_by_name(params[:website][:name])

    #etc... @website.update_attributes
  end
end

The client does not have any IDs of these models

The request that gets sent only has the names, but not the ids.

And the following models

class Website < ActiveRecord::Base
  serialize :website_errors

  attr_accessible :plugins_attributes
  has_many :plugins

  accepts_nested_attributes_for :plugins
end

class Plugin < ActiveRecord::Base
  belongs_to :website
end

When I make a POST request to /websites/save.json, the Website gets updated correctly if it exists, but the Plugins that belong to it always get recreated causing duplicate content in the Database. Why does this happen? I redirect to the update action which calls update_attributes so how can it be that it does not update it? I take it that it's because no ID is given with the request.

Can I make the Controller listen to plugin_name instead of plugin_id?

like image 978
tolgap Avatar asked Aug 29 '13 21:08

tolgap


1 Answers

Modify your controller to have this:

def update
  @website = Website.find_by_name(params[:website][:name])
  if @website.update(params)
    redirect_to website_path(@website)
  else
    render :edit
  end
end

Also, if you're using strong_parameters, you'll need this at the bottom of your controller:

params.require(:website).
  permit(
    :name,
    ...,
    plugins_attributes: [
      :name,
      ...,
    ]
  )
end
like image 174
ryanfelton Avatar answered Oct 02 '22 21:10

ryanfelton