开发者

join table and has_many relationships not working

I have two items, users and posts, and a join table linking them together. The two items have a has_many relationship with each other (:through the join table). I created the join table after creating the two databases. The problem I am having is that I get errors every time I try and do something with @user.posts or @post.users. It is almost like they are not set up correctly. Somewhere I was reading that if you create an association after creating the model, then you have to use the add_column method. Is that my problem? I wasnt sure on how to implement that method or anything. This is the error I get:

SQLite3::SQLException: no such column: users.post_id: SELECT "users".* FROM "users" WHERE "users"."post_id" = 60 AND "users"."id" = ? LIMIT 1

Looks like from the error I need to add a column but im not sure on how to do that.

here is my latest schema.db:

ActiveRecord::Schema.define(:version => 20110930155455) do

  create_table "posts", :force => true do |t|
    t.text开发者_StackOverflow社区     "content"
    t.integer  "vote_count"
    t.text     "author"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  create_table "users", :force => true do |t|
    t.string   "user_name"
    t.string   "password"
    t.date     "time"
    t.integer  "posts_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "post_id"
  end

  create_table "votes", :force => true do |t|
    t.integer  "post_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


Yes, you need to create a migration for the foreign keys. You need to add post_id to the :users table with type integer. Perform

rails g migration AddPostIdToUsers post_id:integer

to generate your migration. You should create one that looks like

class AddPostIdToUsers < ActiveRecord::Migration
  def change
    add_column :users, :post_id, :integer
  end
end

You might also want to consider setting up a *has_many :through association*, it'll give you more control.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜