Association "invalid" while saving model

I have a club model and a member model that are linked through a membership model. In other words

class Club < ActiveRecord::Base has_many :members, :through => :memberships end class Member < ActiveRecord::Base has_many :clubs, :through => :memberships end 

However, when I try to create a new member and add him to the club, I get a message that the club is not valid.

 > club = Club.find(1) > member = Member.new(:name => 'Member Name') > member.clubs << club > member.save 

The member.save will return false. Looking at member.errors.messages, I find

 > member.errors.messages @messages={:clubs=>["is invalid"]} 

It is really strange that this does not happen for my development environment (using sqlite3), but only for my EngineYard deployment using mySQL.

+4
source share
2 answers

I just realized my problem. The My Club class contains a virtual attribute: a password that is used only when creating a club, and otherwise it should be ignored. It turns out that due to an error, the password is not ignored otherwise and is checked when the club association is saved. So, Jim Stewart was right in his comment: the club is actually NOT valid, although I thought it was.

The reason the problem does not occur during the development process is that password checking is disabled in my development environment, so I can test with simple passwords.

+7
source

Do you have a memberships table for both development and production (i.e. you ran rake db:migrate everywhere)?

You may also need to modify your models as follows:

 class Club < ActiveRecord::Base has_many :memberships has_many :members, :through => :memberships end class Member < ActiveRecord::Base has_many :memberships has_many :clubs, :through => :memberships end class Membership < ActiveRecord::Base belongs_to :club belongs_to :member end 
+3
source

All Articles