2012-07-01 100 views
1

如何制作动态变量名称/对象?Rails:用于多态控制器/模型的包装实例变量

我有一个多态模型,用于在批准时发送请求和加入模型。 用户可以加入公司,项目或组等的示例。

所以我有一个属性模型belongs_to各种模型,但我只想要关系建立一旦请求被接受。

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 

我需要我的控制器能够基于它是处理模型以应用于其行动。

我一直希望用@ profile。@ belongs_to和@ profile.company是一样的,在这种情况下,它就是nill。然后从@ profile。@ belongs_to = @requestable

因为配置文件总是属于它加入的模型@belongs_to将始终是小写的模型名称。

我一直在搞乱发布到闪存消息的对象的内容,试图弄清楚这一点。

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: "#{@[email protected]_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 

我已经在控制台的线沿线打得四处财产以后:

profile = Profile.first 
profile.company = Company.first 

,这将创建在随后可以保存对象的连接。

回答

2

如果@belongs_to包含您的关联中,你可以简单的调用@profile.send(@belongs_to)或在分配中@profile.send("#{@belongs_to}=",@requestable)

#send允许你发送任何消息给任何红宝石对象的情况下。想想动态方法调用。

而你应该完成

相关问题