bork121
bork121

Reputation: 113

has_many, belongs_to issues in Rails

I am trying to create a list of directors that have many movies (each movie belongs to one director):

class Director < ActiveRecord::Base
  attr_accessible :director

  has_many :movies
end

class Movies < ActiveRecord::Base
  attr_accessible :director_id, :title, :rating, :boxoffice

  belongs_to :director
end

My schema looks like this:

ActiveRecord::Schema.define(:version => 20130312174246) do

  create_table "directors", :force => true do |t|
    t.string   "director"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "movies", :force => true do |t|
    t.integer  "director_id"
    t.string   "title"
    t.string   "rating"
    t.integer  "boxoffice"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

end

Show in directors controller:

 def show
    @director = Director.find(params[:director_id])
    @movies = @director.movies
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @director }
    end
  end

I would ultimately like to click on a director and see all of the movies he or she has directed, along with the movie's respective ratings and box office $. Currently I get this error: Couldn't find Director without an ID

New to Rails so I'm not sure how to resolve this. Is this the correct setup for what I want to do? If not, how should I change it? Thanks!

Upvotes: 0

Views: 352

Answers (1)

Zippie
Zippie

Reputation: 6088

You should get the director with params[:id], and not with params[:director_id] Try this:

@director = Director.find(params[:id])

To see all of the movies that a director has made do a nested route:

resources :directors do
  resources :movies
end

To make all of the actions work in the MovieController you have to follow the nested route syntax. Find it here: http://guides.rubyonrails.org/routing.html or find the rails for zombies 2 tutorial slides on the web, its also nicely explained there.

Upvotes: 1

Related Questions