[英]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
目前,我收到此错误:没有ID找不到导演
New to Rails so I'm not sure how to resolve this. Rails的新手,所以我不确定如何解决此问题。 Is this the correct setup for what I want to do?
这是我想要做的正确设置吗? If not, how should I change it?
如果没有,该如何更改? Thanks!
谢谢!
You should get the director with params[:id]
, and not with params[:director_id]
Try this: 您应该使用
params[:id]
来获得导演,而不应该使用params[:director_id]
尝试params[:director_id]
:
@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. 要使所有动作在
MovieController
您必须遵循嵌套的路由语法。 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. 在此处找到它: http : //guides.rubyonrails.org/routing.html或在网络上找到僵尸2教程幻灯片的滑轨,那里也有很好的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.