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
?