In my app I have users, schools (groups), and courses. I am trying to set up a model whereby any one of these three models can send any other model a request, and give the request-receiver an option to accept or deny the request. The idea I had was to set up a polymorphic to polymorphic association, so rails would identify the request_sender and receiver’s id and type. My first question is, does it make sense to set up a poly to poly table to achieve this functionality, or should I be trying something different? If a poly to poly table makes sense I included my current controller and db table:
The database table I set up for requests is:
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.belongs_to :request_sender, polymorphic: true
t.belongs_to :requestable , polymorphic: true
t.timestamps
end
add_index :requests, [:request_sender_id, :request_sender_type]
add_index :requests, [:requestable_id, :requestable_type]
end
end
this is my request controller, the problem I am having is defining methods to determine the class of both the request sender and receiver:
def new
@request = @requestable.requests.new
end
def create
@request = @requestable.requests.new(params[:request])
if @request.save
redirect_to @requestable, notice: "requested."
else
render :new
end
end
private
def load_requestable
klass = [School, User, Course].detect { |c| params["#{c.name.underscore}_id"] }
@requestable = klass.find(params["#{klass.name.underscore}_id"])
end
any help or guidance is greatly appreciated as I am new to both programming and rails, and have very little clue what I am doing haha.
Sure, no reason why this can’t work.
what you’ll need when creating a message is to send in the class_name and ID of the creator and receiver. So let’s say your form sends in:
Then, in your MessagesController