简体   繁体   English

在Rails Scaffold中调用创建的对象

[英]Calling created Objects in Rails Scaffold

I am new to Rails and creating a football results app, I did a rails generate Scaffold Team name:string form:string then I added a few teams to the table, my next step I tried was to create a Fixtures table that stores teams, so I did rails generate Scaffold Fixture week:string homeTeam:team awayTeam:team homeScore:integer awayScore:integer when I tried to update the database doing a rake db:migrate I am getting an error undefined method:team I understand rails does not like the way I specify them teams as type team. 我是Rails的新手,并创建了一个足球结果应用程序,我用rails generate Scaffold Team name:string form:string然后向该表中添加了几支球队,下一步我试图创建一个存储球队的Fixtures表格,所以当我尝试使用rake db:migrate更新数据库时,我做了rails generate Scaffold Fixture week:string homeTeam:team awayTeam:team homeScore:integer awayScore:integer我得到一个错误未定义的方法:team我理解Rails不喜欢我将他们指定为类型团队的方式。

How can I go about getting this to work, as when creating a fixture I want to be able to choose from a list of teams already stored in a teams table? 我该如何工作,例如在创建固定装置时希望从已经存储在“团队”表中的团队列表中进行选择?

As a random aside, the convention in ruby/rails is to use underscores as opposed to camelCase for variables and methods. 顺便说一句,在ruby / rails中的约定是使用下划线而不是camelCase来表示变量和方法。

On to your actual question! 关于您的实际问题! You need to setup relationships yourself in the generated Team and Fixture models. 您需要在生成的TeamFixture模型中Fixture设置关系。 Scaffolding can help you setup the relationships though by getting the correct foreign keys in place. 脚手架可以通过正确放置外键来帮助您建立关系。

For the Fixture scaffold, generate it like this: 对于Fixture脚手架,如下生成:

rails g scaffold fixture week:string home_team_id:integer away_team_id:integer home_score:integer away_score:integer

Note that g is a shortcut for generator and the generator doesn't need anything to be capitalized. 请注意, ggenerator的快捷方式, generator器不需要大写。

Now, in your Team model you'll want to define your relationship to the Fixture and vice versa (I'm no sports expert, but wouldn't naming it Game make more sense?): 现在,在您的Team模型中,您需要定义与Fixture之间的关系,反之亦然(我不是体育专家,但是将Game命名为更有意义吗?):

class Team < ActiveRecord::Base
    has_many :home_games, :class_name => Fixture, :foreign_key => :home_team_id
    has_many :away_games, :class_name => Fixture, :foreign_key => :away_team_id
end

class Fixture < ActiveRecord::Base
    belongs_to :home_team, :class_name => Team
    belongs_to :away_team, :class_name => Team
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM