我遇到的情況,該車型看起來像軌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列。 但是不是聯合應該照顧它嗎? 我在這裏做錯了什麼?
感謝您的幫助
一個博客可以有多個用戶(或人誰可以提交)。這是博客和用戶之間的許多關係。不會添加一個user_id列來擊敗該目的? – truthSeekr 2011-05-22 03:09:59
你說得對。 posts表是否打算成爲用戶和博客之間的關聯表?如果是這樣,這些協會是有點關閉。我會編輯我的答案。 – DonaldSowell 2011-05-22 03:25:35
是的,Posts表應該是關聯表。謝謝你的幫助。 – truthSeekr 2011-05-22 03:28:43