Model.Save causing nil object error

Hello all.

Newbie to rails here and I am having a bit of an issue. I have the
following models:

class Topic < ActiveRecord::Base
validates_presence_of :name
validates_length_of :name, :minimum => 3
has_many :relationship_topics
has_many :relationships, :through => :relationship_topics
end

class Relationship < ActiveRecord::Base
has_many :relationship_topics
has_many :topics, :through => :relationship_topic
end

class RelationshipTopic < ActiveRecord::Base
validates_uniqueness_of :topic, :scope => :relationship

belongs_to :relationship
belongs_to :topic
end

Now, here is example code of me trying to create a new
RelationshipTopic:

@rel = RelationshipTopic.new(:relationship_id => 1, :topic_id => 1)
=> #<RelationshipTopic id: nil, relationship_id: 1, topic_id: 1,
primary: nil, created_at: nil, updated_at: nil>

@rel.save
@rel.save
NoMethodError: You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.text?

Why am I unable to use the .save method when creating
RelationshipTopics? Creating relationships and topics by itself works,
but I can’t get the join table to cooperate.

Hi Matthew Shapiro

  I think you are trying for uniq entry in join table(here 

relationship_topics).That you can do on db level In the migration file
for this join table you can add after the creation of the table an index
like

add_index :relationship_topics, [:relationship_id, :topic_id], :unique
=> true

Then migrate as usual.Now the model save can be run inside a begin 

end block
and rescue ActiveRecord::StatementInvalid error…You can also remove
the line

validates_uniqueness_of :topic, :scope => :relationship
from above

Sijo

Excellent, that worked!

Thanks,