I've got 2 models:
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
Relationship create code:
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
But it doesn't work. Looks like hashtags never be saved. What's wrong with this code?
UPD:
Join table:
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
And error:
ActiveRecord::AssociationTypeMismatch: Hashtag(#70233360314580) expected, got TrueClass(#70233335523020)