Answer the question
In order to leave comments, you need to log in
Rails HABTM relationship. How to save?
Hello!
There are 2 models:
class Hashtag < ActiveRecord::Base<br>
has_and_belongs_to_many :photos<br>
attr_accessible :name<br>
***<br>
end<br><br>
class Photo < ActiveRecord::Base<br>
has_and_belongs_to_many :hashtags, :uniq => true<br>
***<br>
end<br>
def up<br>
create_table :hashtags_photos, :id => false do |t|<br>
t.integer :photo_id<br>
t.integer :hashtag_id<br>
end<br><br>
add_index :hashtags_photos, [:photo_id, :hashtag_id], :unique => true<br>
end<br>
def set_hashtags<br>
text.scan(/#+/).each do |workpiece|<br>
next if workpiece.length > 25<br>
hashtag = Hashtag.find_by_name(workpiece)<br>
if hashtag<br>
hashtag.touch<br>
else<br>
hashtag = Hashtag.new(:name => workpiece).save!<br>
end<br>
hashtags << hashtag<br>
end <br>
end<br>
ActiveRecord::AssociationTypeMismatch: Hashtag(#70309985182100) expected, got TrueClass(#70309973845700)<br>
Answer the question
In order to leave comments, you need to log in
hashtag = Hashtag.new(:name => workpiece).save!
I usually explicitly declare the model for the link ( HashtagPhoto in this example)
AND do has_many and has_many :through; (not habtm) I add attr_accessor
to the model, which gives me the related data in the right form
(for example, attr_accessor :hashtags_ids (list of id or whatever else is needed in the context))
and before_save I already create links in the link table.
A bit slick, but reliable
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question