2011-05-22 34 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