我有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
但它不起作用。看起来主题标签永远不会被保存。这段代码有什么问题?
升级版:
连接表:
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)