[英]Rails find method didn't use my foreign key
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: 以下显示操作,从选定主题获取:id:
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. 问题在于, find方法始终采用TopicContent表中的主键(id)而不是外键(topic_id) 。
Is there something wrong with my defined associations? 我定义的关联有问题吗?
.find(primary_key)
always retrieves the records from database based on primary key
. .find(primary_key)
始终基于primary key
从数据库检索记录。
Use .find_by(conditions)
instead as it finds the first record matching conditions passed to it. 使用
.find_by(conditions)
代替,因为它找到传递给它的第一个记录匹配条件。
For eg: 例如:
@text = TopicContent.find_by(topic_id: params[:id])
You need to find the TopicContent via the Topic. 您需要通过主题找到TopicContent。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.