Search code examples
ruby-on-railsdynamicpartialsslim-lang

Dynamic partial name using slim and Rails 4 & getting Partial Name is Not Valid Ruby Identifier Error


I am building a Rails 4 blogging app and using Slim. I am trying to dynamically set the partial name using my 'img_style' column in my Post table. This will call different partials based on different enumerated 'image styles'.

view

= render = 'img_style_{#@post.img_style}'

This should produce the equivalent to:

= render = 'img_style_1'

I'd like this it to be able to render my partial called '_img_style_1.html.slim'

Right now, with the code I have, it just renders this error on the screen:

There is an Error: The partial name (img_style_{#@post.img_style}) is not a valid Ruby identifier; make sure your partial name starts with underscore, and is followed by any combination of letters, numbers and underscores.

Solution

  • Ruby Strings defined with single quotes ('') do not allow expression substitution. You need to use double quotes ("") instead, and also use the proper substitution syntax (# before {):

    "img_style_#{@post.img_style}"
    

    ETA Relatedly, and perhaps you've already done this, but I would make sure that img_style only includes values for which partials are defined using a validation, e.g.:

    validates_inclusion_of :img_style, in: [1,2,3]