.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])
سؤال
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.