2

inside one of my view pages I'm using old fashion way of presenting data but I have problem in converting a string like "User.country.name" to a query statement. I'm using a loop like below :

@columns = ['id','email','name','country.name']

table = User.all

<% table.each do |row| %>
    <% @columns.each do |field| %>
         <%= row[field] %>
    <% end %>
<% end %>

The table shows almost all data except for column "country.name". I can't use constantize for country.name it gives me error. Any solution ? Thanks

1
  • if I write row[field].constantize it shows : NoMethodError in Table#show_table , undefined method `constantize'. Without constantize it shows the id, email and name fields of each row except last one with empty field Commented Jan 28, 2014 at 11:06

2 Answers 2

2

Your User doesn't have an attribute country.name, it has an association country and that association has an attribute name.

You could set up a delegate:

 class User < ActiveRecord::Base
   delegate :name, to: :country, prefix: true
   # ...
 end

This creates a method User#country_name, returning country.name.

Now you can adapt your loop, using public_send to call the methods: (I've changed the variable names to make it clearer)

@methods = [:id, :email, :name, :country_name]

records = User.all

<% records.each do |record| %>
  <% @methods.each do |method| %>
    <%= record.public_send(method) %>
  <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0
@users = User.select(:id, :email).joins(:countries)

<% @users.each do |user| %>
  <%= user.id %>
  <%= user.email %>
  <%= user.countries %>
<% end %>

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-joins

Wish it helps

Comments

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.