Get ActiveRecord attribute by name

I have a partial one that will be used in many places of the project.

It displays elements related to the specified tag, for example:

@tag.articles.each do |a|
    # render articles
end

I need this partial to display not only articles, but also any other elements related to tags.

So, this partial one has a connection_name parameter and looks like this:

@tag[association_name].each do |a|
    # render articles
end

I call it partial as follows:

# to render articles
render :partial => "items", :locals => {:association_name => "articles"}

# to render videos
render :partial => "items", :locals => {:association_name => "videos"}

# etc.

The problem is that I cannot refer to the article model fields in this way:

@article[association_name]

How to do it and why it doesn’t work?

+3
source share
1 answer
@article.send(association_name)
+5
source

Source: https://habr.com/ru/post/1793032/


All Articles