sayid2008 发表于 2013-2-5 02:18:56

宝典:第一式 表间关联easy

在一个程序中不可能只有一个数据表,而表多了之间的关联自然而然就有了
比如:Questions表与Answers表,显然是一对多的关系
如果你在Question和Answers的model中加上
M
class Question < ActiveRecord::Base    has_many :answers   ......end
class Answer< ActiveRecord::Base    belongs_to :question    ......end
C
class QuestionController < ApplicationController    layout 'base'    def index      @question= Question.find(1)      @answer = Answer.find(1)    end      ......end
V中可以轻松的取到
<%=@question.answers.answer_content%> #答案内容answer_content <%=@answer.question.content%>    #问题内容content
http://www.agoit.com/images/smiles/icon_wink.gif
页: [1]
查看完整版本: 宝典:第一式 表间关联easy