Rails无法创建HABTM关系

时间:2012-10-19 06:00:50

标签: ruby-on-rails activerecord has-and-belongs-to-many

我有2个型号:

class Hashtag < ActiveRecord::Base
  has_and_belongs_to_many :photos
  attr_accessible :name
***
end

class Photo < ActiveRecord::Base
  has_and_belongs_to_many :hashtags, :uniq => true
***
end

关系创建代码:

photo = current_user.photos.new( params[:photo] )
if !photo.nil? and photo.save!
    photo.text.scan(/#[[:alnum:]]+/).each do |billet|
            next if billet.length > 25
            hashtag = Hashtag.first_or_initialize(:name => billet)
            if hashtag.persisted?
                hashtag.touch
            else
                hashtag.save!
            end
            photo.hashtags << hashtag
        end
    render json: photo
end

但它不起作用。看起来像哈希标签永远不会被保存。这段代码出了什么问题?

UPD:

加入表:

def up
    create_table :hashtags_photos, :id => false do |t|
      t.integer :photo_id
      t.integer :hashtag_id
    end

    add_index :hashtags_photos, [:photo_id, :hashtag_id], :unique => true
  end

错误:

ActiveRecord::AssociationTypeMismatch: Hashtag(#70233360314580) expected, got TrueClass(#70233335523020)

1 个答案:

答案 0 :(得分:0)

正确的方法:

text.scan(/#[[:alnum:]]+/).each do |workpiece|
        next if workpiece.length > 25
        hashtag = Hashtag.find_by_name(workpiece)
        if hashtag
          hashtag.touch
        else
          hashtag = Hashtag.create!(:name => workpiece)
        end
        hashtags << hashtag
end