无法设置 ActiveRecord 多对多关系
Trouble setting up ActiveRecord many to many relationship
我在 Rails 应用程序中建立多对多关系时遇到了一些困难。我是 运行 Ruby 2.2.2p95 和 Rails 4.2.0.
NoMethodError: undefined method `each' for #<Topic id: 1>
seeds.rb:63:in `<top (required)>'
我的视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topic
end
题目模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :video
end
加入table迁移:
class TopicsVideos < ActiveRecord::Migration
def up
create_table :topics_videos, id: false do |t|
t.belongs_to :topic_id, index: true
t.belongs_to :video_id, index: true
end
end
def down
drop_table :topics_videos
end
end
db seeder 中发生错误:
62 | @topicTest= Topic.create!(title: 'Test')
63 | Video.create!(title: 'Test', topic: @topicTest)
我对 Rails 还是很陌生,来自 PHP,现在这个问题让我很困惑。任何帮助将不胜感激。
你需要像这样将关系模型复数化:
视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topics
end
题目模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :videos
end
首先has_and_belongs_to_many
协会名称应该是复数。
视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topics
end
主题模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :videos
end
然后就可以使用create
has_and_belongs_to_many
添加的方法了
@topicTest= Topic.create!(title: 'Test')
@topicTest.videos.create!(title: 'Test')
或
@topicTest= Topic.create!(title: 'Test')
@topicNew= Topic.create!(title: 'New')
video = Video.create!(title: 'Test')
@topicTest.videos << video
@topicNew.videos << video
我在 Rails 应用程序中建立多对多关系时遇到了一些困难。我是 运行 Ruby 2.2.2p95 和 Rails 4.2.0.
NoMethodError: undefined method `each' for #<Topic id: 1>
seeds.rb:63:in `<top (required)>'
我的视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topic
end
题目模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :video
end
加入table迁移:
class TopicsVideos < ActiveRecord::Migration
def up
create_table :topics_videos, id: false do |t|
t.belongs_to :topic_id, index: true
t.belongs_to :video_id, index: true
end
end
def down
drop_table :topics_videos
end
end
db seeder 中发生错误:
62 | @topicTest= Topic.create!(title: 'Test')
63 | Video.create!(title: 'Test', topic: @topicTest)
我对 Rails 还是很陌生,来自 PHP,现在这个问题让我很困惑。任何帮助将不胜感激。
你需要像这样将关系模型复数化:
视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topics
end
题目模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :videos
end
首先has_and_belongs_to_many
协会名称应该是复数。
视频模型:
class Video < ActiveRecord::Base
has_and_belongs_to_many :topics
end
主题模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :videos
end
然后就可以使用create
has_and_belongs_to_many
@topicTest= Topic.create!(title: 'Test')
@topicTest.videos.create!(title: 'Test')
或
@topicTest= Topic.create!(title: 'Test')
@topicNew= Topic.create!(title: 'New')
video = Video.create!(title: 'Test')
@topicTest.videos << video
@topicNew.videos << video