Ruby on rails rails有许多贯穿数据插入的问题
我有一个场景,模型看起来像Ruby on rails rails有许多贯穿数据插入的问题,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个场景,模型看起来像 create_table :users do |t| t.string :name t.timestamps end create_table :blogs do |t| t.string :url t.string :title t.text :description t.timestamps end create_table :posts do |t| t.integer :user_id, :null => false
create_table :users do |t|
t.string :name
t.timestamps
end
create_table :blogs do |t|
t.string :url
t.string :title
t.text :description
t.timestamps
end
create_table :posts do |t|
t.integer :user_id, :null => false
t.integer :blog_id, :null => false
t.text :post_text
end
class Blog < ActiveRecord::Base
has_many :users, :through =>:posts
has_many :posts, :dependent=>true
end
class User < ActiveRecord::Base
has_many :blogs
has_many :posts, :through=>:blogs
end
class Post < ActiveRecord::Base
belongs_to :blog
belongs_to :user
end
我知道Blogs表没有user\u id列。
但是,联合会不应该负责吗?
我做错了什么
感谢您的帮助使用Post模型作为关联表,需要调整用户模型以正确演示关联。完成后,您可以在创建后使用
为新创建的用户创建新博客
class User < ActiveRecord::Base
has_many :posts
has_many :blogs, :through=>:posts
after_create :add_blog
private
def add_blog
blogs << Blog.new
end
end
如果5是真的,这将是一个真正的多对多。。。但我不认为这就是你想要做的。一个博客可以有多个用户(或者可以提交的人)。博客和用户之间是一种多对多的关系。添加一个user\u id列不会破坏这个目的吗?你是对的。posts表是用户和博客之间的关联表吗?如果是这样的话,这种联系就有点离谱了。我将编辑我的答案。是的,Posts表应该是关联表。谢谢你的帮助。很乐意帮忙。希望当前的、综合的/澄清的答案能起到作用。我运行了代码,我想我看到了发生的事情。。。我认为在你试图做的和实际做的之间仍然存在差异。我试图在这篇评论中解释这一切,但已经没有空间了。因此,我将编辑我的答案以提供清晰性。
Mysql::Error: Unknown column 'blogs.user_id' in 'where clause': SELECT * FROM `blogs` WHERE (`blogs`.user_id=1234)
class User < ActiveRecord::Base
has_many :posts
has_many :blogs, :through=>:posts
after_create :add_blog
private
def add_blog
blogs << Blog.new
end
end
class Blog < ActiveRecord::Base
belongs_to :users,
has_many :posts, :dependent=>:destroy # rec'd error in RoR3... replaced true with :destroy
end
class User < ActiveRecord::Base
has_many :blogs, :dependent=>:destroy
has_many :posts
after_create :add_blog
private
def add_blog
blogs << Blog.new
end
end
class Post < ActiveRecord::Base
belongs_to :blog
belongs_to :user
end