Rails 数据库播种
由于某种原因,当我运行下面的 Seed.rb 文件时,“评级”中的 food_id 字段没有填充。有人可以帮我弄清楚为什么吗?
种子文件包含以下行:
Food.create(:id => 1, :description => 'Stonyfield Farm Yomommy 4oz. Strawberry')
OverallRating.create(:score => 0, :count => 1, :food_id => 1)
食品和评级代码如下: 班级总体评分<等级 属于:食物 评级
class Food < ActiveRecord::Base
has_one :overall_rating
end
class Rating < ActiveRecord::Base
belongs_to :food
end
迁移文件如下:
class CreateRatings < ActiveRecord::Migration
def self.up
create_table :ratings do |t|
t.integer :food_id
t.integer :count
t.decimal :score
t.string :type
t.timestamps
end
end
def self.down
drop_table :ratings
end
end
For some reason, the food_id field in 'ratings' isn't populating when I run the seed.rb file below. Can somebody help me figure out why?
Seed file contains the following lines:
Food.create(:id => 1, :description => 'Stonyfield Farm Yomommy 4oz. Strawberry')
OverallRating.create(:score => 0, :count => 1, :food_id => 1)
Code for Food and Rating are as follows:
class OverallRating < Rating
belongs_to :food
end
class Food < ActiveRecord::Base
has_one :overall_rating
end
class Rating < ActiveRecord::Base
belongs_to :food
end
The rating migration file is as follows:
class CreateRatings < ActiveRecord::Migration
def self.up
create_table :ratings do |t|
t.integer :food_id
t.integer :count
t.decimal :score
t.string :type
t.timestamps
end
end
def self.down
drop_table :ratings
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你如何调用 seeds.rb 文件?您可能需要执行
rake db:seed
how are you invoking the seeds.rb file? You may have to do a
rake db:seed
这真的是实际的代码吗?我猜想您在评级/总体评级中有一个 attr_accessible 或 attr_protected 声明,这会阻止在实例化对象中设置该选项。
Is that really the actual code? I would guess you've got an attr_accessible or attr_protected declaration in Rating/OverallRating that is preventing the option from being set in the instantiated object.
不要对
id
进行硬编码,而是尝试这样的事情:我只是尝试了你的确切方法,它对我来说没有问题。所以也许你还有其他问题。
Instead of hardcoding the
id
, try something like this:I just tried your exact method though, and it worked for me without a problem. So perhaps you have something else awry.