2011-05-22 30 views
0

我遇到的情况,该车型看起来像轨has_many_through数据插入问题

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 

我的问题是: 1.当创建一个用户,我想自动创建一个博客给他。

@user = User.find_or_create_by_name(USER_NAME)

如何去创建一个博客? @blog = Blog.find_or_create_by_user_id(@user)

我收到以下错误:

undefined method `find_or_create_by_user_id' for #<Class:0x1044735b0> 

@blogs = @user.blogs 

给我:

Mysql::Error: Unknown column 'blogs.user_id' in 'where clause': SELECT * FROM `blogs` WHERE (`blogs`.user_id=1234) 

我知道博客表没有user_id列。 但是不是联合应该照顾它吗? 我在这里做错了什么?

感谢您的帮助

回答

2

使用POST模型作为关联表,用户模型需要进行调整,以正确展示的关联。完成后,您可以使用after_create为新创建的用户创建新的博客。

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 

编辑:

我知道如何处理这是解释我“想”的关系,试图实现,那么你告诉我在哪里,我离,我们从那里最好的。

1)用户可以“拥有”许多博客

2)博客可以有很多帖子

3)交属于单个用户和到单个博客

4)一个博客只能通过许多用户,从而给他们的权限后有一个“所有者”(用户)

5)博客可以“拥有”。

如果1-4是真的,5假的... ...这不是一个“的has_many:通过”方案,或许多一对多的关系,只是一个一对多的关系。

因此,帖子不应该被用作关联表。没有需要的关联表。

添加t.integer :user_id, :null => false到博客表

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 

如果5是真的,这将是一个真正的多到很多......但我不认为这是你试图做什么。

+0

一个博客可以有多个用户(或人谁可以提交)。这是博客和用户之间的许多关系。不会添加一个user_id列来击败该目的? – truthSeekr 2011-05-22 03:09:59

+1

你说得对。 posts表是否打算成为用户和博客之间的关联表?如果是这样,这些协会是有点关闭。我会编辑我的答案。 – DonaldSowell 2011-05-22 03:25:35

+0

是的,Posts表应该是关联表。谢谢你的帮助。 – truthSeekr 2011-05-22 03:28:43