Relations tables in RoR

There are two tables: user and order:

create_table "orders" do | t |
t.text "name"
t.integer "user_id"
end

create_table "users" do | t |
t.text "email"
end

Two classes:

class Order <ActiveRecord :: Base
  belongs_to: users
end

class User <ActiveRecord :: Base
   has_many: orders
end

Сontroller:

class TestController <ApplicationController
   def index
     @ tmp = Order.all(:include =>:users)
   end
end

Question: I need all orders but instead of user_id the email associated with the user_id is returned

Upvotes: 2

Views: 51

Answers (2)

I do not have the reputation to comment, but about the order.user.email issue, use the try method:

order.user.try(:email)

If the user is nil, it just return nil, instead of raising a exception.

Upvotes: 1

martincarlin87
martincarlin87

Reputation: 11062

Welcome to Stack Overflow, I'm new to Rails myself but try this:

@tmp = Order.all(
              :select => 'orders.id, orders.etc, users.email',
              :joins => "LEFT JOIN users on users.id = orders.user_id",
              # :conditions => ['column_name = ?', @value_of_your_choice],
              :order => 'orders.created_at ASC'
            )

You could also try this:

class TestController < ApplicationController
  def index
    @tmp = Order.all()
  end
end

Then, in the view:

<% @tmp.each do |order| %>

  <!-- do not show if orders.user.id is NULL -->
  <% if !order.user_id.nil? %>
    <tr>
      <td><%= order.id %></td>
      <td><%= order.user.email %></td>
    </tr>
  <% end %>
<% end %>

Since the relations between the two models are defined, you can access the properties of the associated person in this way.

You might need to change the belongs_to: users to belongs_to: user in user.rb though

Upvotes: 1

Related Questions