سؤال

I have the following two Models:

class TopicContent < ActiveRecord::Base
 unloadable
 belongs_to :topic 
end

and

class Topic < ActiveRecord::Base
 unloadable
 has_one :topic_content
 accepts_nested_attributes_for :topic_content
end

And the following show action, which get the :id from the selected topic:

def show
 @text = TopicContent.find(params[:id])
end

The problem is, that the find method always take the primary-key(id) instead of foreign-key (topic_id) from the TopicContent table.

Is there something wrong with my defined associations?

هل كانت مفيدة؟

المحلول

.find(primary_key) always retrieves the records from database based on primary key.

Use .find_by(conditions) instead as it finds the first record matching conditions passed to it.

For eg:

@text = TopicContent.find_by(topic_id: params[:id])

نصائح أخرى

You need to find the TopicContent via the Topic.

def show
  @topic = Topic.find(:topic_id)
  @text = @topic.topic_content
end

This is assuming you have your routes set up as well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top