Activerecord多对多关系无法正常工作

时间:2015-01-22 00:19:31

标签: ruby-on-rails activerecord rails-activerecord

我正在研究一个推特克隆,并且我的一些协会遇到了麻烦。我希望用户有很多推文。我的推文与主题标签有多对多的关系,所以理论上我希望能够调用User.find(1).hashtags并有一个用户的主题标签列表(编辑:解决了这个问题)。我也无法将主题标签推送到特定的推文中。

以下是我的模特:

class User < ActiveRecord::Base
  has_many :tweets
end

class Tweet < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :hashtags
end 

class Hashtag < ActiveRecord::Base
  has_and_belongs_to_many :tweets
end

以下是我的迁移:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username
      t.string :email
      t.string :password

      t.timestamps
    end
  end
end

class CreateTweets < ActiveRecord::Migration
  def change
    create_table :tweets do |t|
      t.string :content
      t.belongs_to :user

      t.timestamps
    end
  end
end

class CreateHashtags < ActiveRecord::Migration
  def change
    create_table :hashtags do |t|
      t.string :tag

      t.timestamps
    end
  end
end

class CreateHashtagsTweets < ActiveRecord::Migration
  def change
    create_table :hashtags_tweets, id: false do |t|
      t.references :hashtag
      t.references :tweet
    end
  end
end

任何帮助将不胜感激!谢谢!

0 个答案:

没有答案