Reputation: 992
From my client, I am sending an object that is related to other objects:
var data = { "comment": result.comment, "doc": { "id": result.doc.id } "site": { "url": result.site.url } }; $.ajax({ url: '/data', type: 'POST', data: data });
This gets posted to my /data
controller. In the create
method, I have this block of code:
def create @data = Data.new(params[:data]) @data.user_id = current_user.id respond_to do |format| if @data.save @doc = Doc.find_or_create_by_id(params[:doc]) @doc.save @site = Site.new(params[:site]) @site.doc_id = @doc.id @site.save format.html //stuff format.json //stuff format.js //stuff end end
I'm curious if I am approaching this problem correctly. For related objects like the one I have, the controller seems to be pretty 'heavy'.
Are there any other solutions to this problem out there?
EDIT:
Data model:
class Data belongs_to :site, :polymorphic => true belongs_to :user end
Upvotes: 0
Views: 376
Reputation: 5437
How does your data model looks like? Do you have assignment methods for all nested attributes?
def create
@data = Data.new(params[:data])
@data.user = current_user
respond_to do |format|
if @data.save
@doc = Doc.find_or_create_by_id(params[:doc][:id])
@site = @doc.sites.create(params[:site])
format.html //stuff
format.json //stuff
format.js //stuff
end
end
You can see more details about Active Record Relations in the Rails Guides.
Upvotes: 2