开发者

Rails, get Class from Class name?

开发者 https://www.devze.com 2023-01-17 09:20 出处:网络
I have an issue here where I\'m trying to call a class method on an object that is not known... err, I\'m not sure how to phrase this I\'m getting the :resource from the URL, but I want to run find on

I have an issue here where I'm trying to call a class method on an object that is not known... err, I'm not sure how to phrase this I'm getting the :resource from the URL, but I want to run find on it for a differnt param as well.

How can I do something like:

params[:resource].classify.find(params[:id])

I mean this won't work because the params[:resource].classify would be a string. But how can I run a method on it as if it was a Class and not a string?

The following used to work fine but the gem friendly_id has made all my calls to a record to return it's friendly_id and not its actual primary key... which totally sucks.

It was doing something like this, which worked just fine:

@vote = Vote.new({
  :vote =>开发者_如何学Python; params[:direction] == 'up' ? true : false,
  :voteable_type => params[:resource].classify,
  :voteable_id => params[:id])
})

But since adding friendly_id my paths now look something like:

/things/my-thing-name/vote/up

instead of the old way:

/things/328/vote/up

So now the params[:id] is no longer the foreign key.

Thoughts?


I'm a bit confused by your question, it seems like 2.

For part 1, you can constantize. params[:resource].classify.constantize should return the classname that you can then invoke a method on. Just to be safe, you might want to tableize before constantizeing, just to make sure things like "-" are going to be "_". I only mention this because of how you have your friendly_id set up.

As for part 2, I don't know the friendly_id gem, but based off of the description of how it works in the guide, your find should still work just fine unless I'm missing something.


For the first thing "params[:resource].classify" you need to do

params[:resource].constantize

For the second it looks like you should do something like:

@thing = Thing.find_by_friendly_id(params[:friendly_id])
0

精彩评论

暂无评论...
验证码 换一张
取 消