开发者

Why isn't Rails automatically creating join table entries?

I have a simple has_many through relationship set up:

class Tag < A开发者_JS百科ctiveRecord::Base
  has_many :profile_tags
  has_many :profiles, :through => :profile_tags
end

class ProfileTags < ActiveRecord::Base
  belongs_to :profile
  belongs_to :tag
end

class Profile < ActiveRecord::Base
  has_many :profile_tags
  has_many :tags, :through => :profile_tags
end

From my view I am accepting a set of tags (just strings), and am iterating over them in my controller and calling Tag.create( ... ) on each of them, and pushing them into an array. This all works fine.

So I get to a point where I have an Array of Tag objects (tags) which were each returned by the call to create, and variable @profile which was created by doing Profile.new

I would like to do: @profile.tags = tags

Doing this causes this error on the line where I try the assignment:

uninitialized constant Profile::ProfileTag

Rails is acting like I need to manually create and assign the join table association, even though here http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association it states that when you do an assignment like this, new associations will be created and if some are gone they will be deleted.

Any ideas what I could be doing wrong here?


Rails assumes that model classes are named with the singular form, i.e. the class ProfileTags should be called ProfileTag.

Depending on which Rails version you are using, probably the easiest way to fix this is to re-create the model using script/destroy and script/generate in Rails 2.x or rails destroy and rails generate in Rails 3.

Alternatively, specifying the class name manually by adding :class_name => 'ProfileTags' to the has_many declarations should work too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜