我有一个与投票、评论和帖子的多态关联,如下所示:
class Vote < ActiveRecord::Base
belongs_to :voteable, polymorphic: true
end
class Post < ActiveRecord::Base
has_many :votes, as: :voteable
end
class Comment < ActiveRecord::Base
has_many :votes, as: :voteable
end
当我点击投票链接时,我在参数中发送了 voteable_type
和 voteable_id
。在投票 Controller 中,我想使用这两个字符串找到可投票对象,但我找到的唯一解决方案是 eval。我认为从参数中评估字符串不是一个好主意。
class VotesController < ApplicationController
def find_voteable
@voteable = eval("#{params[:vote][:voteable_type]}.find(params[:vote][:voteable_id])")
end
end
关于如何通过类名和 ID 查找 ActiveRecord 对象有什么建议吗?或者,是否有更好的方法来执行此操作而不在参数中发送内容?
最佳答案
你可能想使用
params[:vote][:voteable_type].classify.constantize.find(params[:vote][:voteable_id])
或者还有
Object.const_get(params[:vote][:voteable_type]).find(params[:vote][:voteable_id])
也检查一下
关于ruby-on-rails - 按类名和 ID 查找 ActiveRecord 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641793/