Rails 数据库播种

发布于 2024-09-09 01:48:19 字数 795 浏览 2 评论 0原文

由于某种原因,当我运行下面的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

安静 2024-09-16 01:48:19

你如何调用 seeds.rb 文件?您可能需要执行rake db:seed

how are you invoking the seeds.rb file? You may have to do a rake db:seed

遗弃M 2024-09-16 01:48:19

这真的是实际的代码吗?我猜想您在评级/总体评级中有一个 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.

青丝拂面 2024-09-16 01:48:19

不要对 id 进行硬编码,而是尝试这样的事情:

food = Food.create(:description => 'blah')
food.create_overall_rating(:score => 0, :count => 1)

我只是尝试了你的确切方法,它对我来说没有问题。所以也许你还有其他问题。

Instead of hardcoding the id, try something like this:

food = Food.create(:description => 'blah')
food.create_overall_rating(:score => 0, :count => 1)

I just tried your exact method though, and it worked for me without a problem. So perhaps you have something else awry.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文