I'm using the has_many_polymorphs plugin so that videos, topics, and users can be posted to profiles. Therefore, a profile has many "showable_objects" which can be videos, topics, and users. Also, the user who creates the "showable_object" will also be associated with it. I've already set up the model associations (below).
The way I want a showable_object to be created is for a user to select another user from an autocomplete field on the show page of the resource. Then that resource is associated with the profile of the selected user.
My question is how should I be setting up my showable_objects controller? Also, if I want it to be sent via AJAX, what will the AJAX jQuery request look like?
UPDATE:
Here are my model associations:
class ShowableObject < ActiveRecord::Base
belongs_to :showable_object, :polymorphic => true
belongs_to :user
belongs_to :profile
end
class Profile < ActiveRecord::Base
has_many_polymorphs :showable_objects, :from => [:videos, :users, :topics, :video_votes],
:dependent => :destroy
end
class User < ActiveRecord::Base
has_many_polymorphs :showable_objects, :from => [:videos, :users, :topics, :video_votes],
:dependent => :destroy
end
This is my ShowableObject migration:
class CreateShowableObjects < ActiveRecord::Migration
def self.up
create_table :showable_objects do |t|
t.references :showable_object, :polymorphic => true
t.references :profile
t.references :user
t.timestamps
end
end
def self.down
drop_table :showable_objects
end
end
By the way I'm also getting this error from these associations (so this is actually a two part question :P):
ActiveRecord::Associations::PolymorphicError in Videos#index
Showing /rubyprograms/dreamstill/app/views/videos/_video.html.erb where line #24 raised:
Could not find a valid class for :showable_objects_users (tried ShowableObjectsUser). If it's namespaced, be sure to specify it as :"module/showable_objects_users" instead.
It points to this line <% if video.owned_by? current_user %>
and has to do with the has_many_polymorphs
call in the user model.
I've never used it, just presently doing some research, but I noticed that you have tagged your question with rails-3 and to my understanding, has_many_polymorphs doesn't work with it. I have found the following fork which might help with the error: has_many_polymorphs by jystewart for rails 3.
来源:https://stackoverflow.com/questions/5768764/how-to-set-up-these-crud-controller-actions-for-has-many-polymorphs-and-an-error