SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: loop problems.

  1. #1
    SitePoint Addict
    Join Date
    Jan 2006
    Posts
    268
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    loop problems.

    Alright, I'm still green with ruby, so excuse my ignorance..
    I've got a number of columns in a user table that I want to loop through..

    I'm doing something like:
    Code:
     <%
        cols = %w(phone_number aim_sn msn_sn)
        cols.each do |c|
          if !empty?(@user.c)
     %>
        <span><%= @user.c %></span>
     <%
          end
        end
      %>
    I'm getting an error says "undefined method `c'"

    how do I get it so it uses c dynamically, instead of as the character c??
    Or if you think my code is absolutely silly, let me know how i _should_ be doing it..

    Thanks

  2. #2
    SitePoint Zealot
    Join Date
    Jul 2005
    Posts
    124
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I believe all of an ActiveRecord object's attributes are stored in an attributes hash, so the following should work:

    Code:
    <% for attribute in @user.attributes %>
      <% unless attribute.empty? %>
        <span><%= attribute %></span>
      <% end %>
    <% end %>

  3. #3
    SitePoint Addict
    Join Date
    Jan 2006
    Posts
    268
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    that works for displaying all the fields, but I'm only trying to show the specific ones listed. is there a way to modify that?

  4. #4
    SitePoint Wizard silver trophy redemption's Avatar
    Join Date
    Sep 2001
    Location
    Singapore
    Posts
    5,269
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    Code:
    <%
      cols = [:phone_number, :aim_sn, :msn_sn]
      cols.each do |c|
        value = @user.send c
        if !empty?(value)
    %>
      <span><%= value %></span>
    <%
        end
      end
    %>
    I just typed it out so there may be some errors. In any case, the send method is probably what you want here.

  5. #5
    SitePoint Addict
    Join Date
    Jan 2006
    Posts
    268
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Worked like a charm, thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •