Arun
Arun

Reputation: 675

Adding variable to make dynamic Ruby statement

I am having trouble creating a dynamic statement in a Rails ERB template. This is essentially what I'm trying to do:

<%= photo.@photo_col.url %>

This will make the statement dynamic based on this condition in the controller:

if !params[:cat]
    @my_photos = BusinessPhoto.where(contributor_id: session[:user_id])
    @photo_col = "business_photo"
elsif params[:cat] && params[:cat] == "event"
    @my_photos = EventPhoto.where(contributor_id: session[:user_id])
    @photo_col = "event_photo"
elsif params[:cat] && params[:cat] == "blog"
    @my_photos = BlogPhoto.where(contributor_id: session[:user_id])
    @photo_col = "post_photo"
end

Can anyone see a problem with this statement?

Upvotes: 0

Views: 41

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37419

I'm not sure what photo is, so there might be a more straight forward way, but what you are trying to do is call a method by its name dynamically. You do that using public_send:

<%= photo.public_send(@photo_col).url %>

Upvotes: 2

Related Questions