0

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?

2
  • You could remove params[:cat] && without breaking anything. It has no practical effect here. Commented Dec 9, 2014 at 19:07
  • Tweaked the code further for fun, if you're interested: gist.github.com/henrik/55066739a6e2147168a3 Commented Dec 9, 2014 at 19:14

1 Answer 1

2

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 %>
Sign up to request clarification or add additional context in comments.

3 Comments

Beautiful, thank you! I knew it had to be something simple :)
Just be careful that the user can't set the @photo_col freely (i.e. never do @photo_col = params[:col]). If a user would pass in the column name "destroy", for example, they would cause the photo to be removed from the database :)
@Arun - if photo is an ActiveRecord, you might want to try photo[@photo_col].url instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.