How do I make a dynamic variable name/object?
I have a polymorphic model for sending request and joining models together upon approval.
Example a user can join a company, project or group ect.
so I have a profiles model that belongs_to various models, but I only want the relationship to be built once a request is accepted.
profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :company
has_many :requests
has_many :requested, as: :requestable
attr_accessible :first_name, :last_name
validates :first_name, presence: true
validates :last_name, presence: true
end
I need my controller to be able to apply its actions based on the model that it is dealing with.
I was hoping that with @profile.@belongs_to would be the same as @profile.company which in this case would be nill. Then from there @profile.@belongs_to = @requestable
because the profile is always going to belong_to the model it joins @belongs_to will always be the model name in lowercase.
I have been messing around with the contents of objects posted to a flash message, to try and figure this out.
requests_controller.rb
class RequestsController < ApplicationController
before_filter :load_requestable
def accept
@request = Request.find(params[:id])
@profile = Profile.find(@request.profile.id)
redirect_to [@requestable, :requests], notice: "#{@profile.@belongs_to} #{@request.profile.first_name} #{@request.profile.last_name} id: #{@request.profile.id} wants to join #{@requestable.name} id: #{@requestable.id}"
end
private
def load_requestable
klass = [Company, Profile].detect { |c| params["#{c.name.underscore}_id"]}
@requestable = klass.find(params["#{klass.name.underscore}_id"])
@belongs_to = klass.to_s.downcase
end
end
I have played around in the console with somthing along the lines of:
profile = Profile.first
profile.company = Company.first
and this creates the join in the object which can then be saved.
If
@belongs_tocontains your association you can simple call@profile.send(@belongs_to)or in case of an assignment@profile.send("#{@belongs_to}=",@requestable)#sendallows you to send any message to any object in ruby. Think dynamic method invocation.And you should be done