开发者

rails has_many_through data insertion question

I have a scenario where the models look like

开发者_如何学Pythoncreate_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

The question I have is: 1. When a user is created, I would like to create a blog for him automatically.

@user = User.find_or_create_by_name(user_name)

How do I go about creating a blog? @blog = Blog.find_or_create_by_user_id(@user)

I am getting the following error:

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

@blogs = @user.blogs

gives me:

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

I know Blogs table does not have user_id column. But isn't the join supposed to take care of it? What am I doing wrong here?

Thanks for your help


To use the Post model as the association table, the User model needs to be tweaked to properly demonstrate the association. Once done, you could use after_create to create a new blog for a newly created user.

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

EDIT:

The best I know how to handle it is to explain what I "think" the relationships are attempting to accomplish then you tell me where I'm off and we go from there.

1) A User can "own" many blogs

2) A blog can have many posts

3) A post belongs to a single user and to a single blog

4) a blog can only have one "owner" (user)

5) Blogs can be "owned" by many users thereby giving them permission to post.

If 1-4 are true, and 5 false... that isn't a "has_many :through" scenario or many-to-many relationship, just one-to-many relationships.

Accordingly, posts should not be used as an association table. There isn't an association table needed.

add t.integer :user_id, :null => false to the blogs table

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

If 5 is true, this would be a true many-to-many... but I don't think that's what you're attempting to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜