0

I have the following:

Schema

create_table "mouldings", :force => true do |t|
  t.string   "suppliers_code"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "name"
  t.integer  "supplier_id"
  t.decimal  "length"
  t.decimal  "cost"
  t.decimal  "width"
  t.decimal  "depth"
end

create_table "suppliers", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Models

class Moulding < ActiveRecord::Base

  # Set up associations
  belongs_to :suppliers

end

class Supplier < ActiveRecord::Base

  # Associations
  has_many :mouldings, :dependent => :destroy

end

Controller

  def show
    @moulding = Moulding.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @moulding }
    end
 end

I want to join the two tables so I can include the supplier's name in a view. What is the correct syntax for the controller?

1
  • You might want to mention Ruby in more than just the tags. Title and body might be useful. Commented Nov 8, 2010 at 17:27

2 Answers 2

4

First off your syntax is a bit off in your moldings model. It's should be supplier singular

class Moulding < ActiveRecord::Base

  # Set up associations
  belongs_to :supplier

end

If you want the supplier name use this in the controller or view.

@moulding.supplier.name

Also if you're going to be looping through a bunch of moldings you'll want to include suppliers in your initial query so it doesn't run a query for each time it lists a suppliers name. The syntax for that is:

@moulding = Moulding.find(params[:id],:include => :supplier)

I'd also suggest taking a look at the official Active Record Associations and Query Interface guides (for Rails 3)

Sign up to request clarification or add additional context in comments.

3 Comments

@freshest You may get some use out of guides.rubyonrails.org. Check the sections on active record query interface, layout and rendering, and action controller overview in particular.
dub Many thanks for the help. If I use Moulding.find(params[:id],:include => :supplier) in the controller what syntax do I use in the view to reference the supplier name?
The syntax doesn't change from what i posted above. The only difference if that if you were to say want to get the supplier names of 1000 moldings this would be a significant performance boost.
1

From a broad perspective, you can use either :joins or :include in your ActiveRecord statement. The major difference is that joins will do an inner join while include will do an outer join. http://asciicasts.com/episodes/181-include-vs-joins

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.