Rails的发现方法没有用我的外键

问题描述:

我有以下两种型号:Rails的发现方法没有用我的外键

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

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

而下面的表演动作,这得到:从选定的主题ID :

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

的问题是,该找到方法始终以主键(id)而不是来自TopicContent表的外键(topic_id)

我定义的关联有什么问题吗?

.find(primary_key)总是根据primary key从数据库检索记录。

使用.find_by(conditions)代替它,因为它发现传递给它的第一条记录匹配条件。

对于如:

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

** Thx **我使用动态的方式,这也工作: @text = TopicContent.find_by_topic_id(params [:id]) – dot

+0

很高兴帮助:) –

你需要找到通过主题的TopicContent。

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

这是假设你也设置了你的路线。