2010-11-10 42 views
1

嗨我目前正在用rails(3)構建一個小的論壇應用程序。我在Rails的問題上相當新,並且陷入了一些主題。belongs_to rails中的對象

我有2款(主題& topic_reply)

主題模型:

class Topic < ActiveRecord::Base 
    belongs_to :board 
    belongs_to :user 
    has_many :topic_replies, :dependent => :destroy 

    TOPIC_TYPES = ["Non-support", "Question"] 
    validates :topic_type, :inclusion => TOPIC_TYPES 
end 

主題回覆型號:

class TopicReply < ActiveRecord::Base 
    belongs_to :topic 
    belongs_to :user 
end 

當我創建一個話題一切,除了被罰款顯示爲topic_replies(主題內的所有帖子)

原因是:我的topic_reply對象保存所有東西,除非它不保存對象中的topic_id,因此保存在我的數據庫中。

這裏是我的話題控制器的一部分,以創建一個話題:

# GET /topics/new 
    # GET /topics/new.xml 
    def new 
    @topic  = Topic.new 
    @topic_reply = @topic.topic_replies.build 

    respond_to do |format| 
     format.html # new.html.erb 
    end 
    end 

    # POST /topics 
    # POST /topics.xml 
    def create 
    @topic     = Topic.new(params[:topic]) 
    @topic.id_board  = @board.id 

    @topic_reply = @topic.topic_replies.build(params[:topic_reply]) 
    @topic_reply.id_topic = @topic.id 
    @topic_reply.id_poster = User.first.id 

    respond_to do |format| 
     if @topic.save && @topic_reply.save 
     format.html { redirect_to(topic_path("#{@board.name.parameterize}-#{@board.id}", "#{@topic.title.parameterize}-#{@topic.id}")) }  
     else 
     format.html { render :action => "new" } 
     end 
    end 
    end 

沒有任何人有一個想法是什麼,我做錯了,如果我張貼過少的信息讓我知道我會添加你需要什麼。提前

回答

3

你的外鍵

感謝應命名爲topic_idposter_idboard_id在Rails的這些默認值。您沒有在模型中定義非默認列,所以當前的代碼無法工作。

+0

剛剛試過,它的工作。如何在一個模型btw中定義非默認列? – Ayrton 2010-11-10 14:17:57

+1

我會建議使用傳統的。更改爲非默認值需要做更多的事情才能產生相同的效果。當然有時候你真的需要它(比如你有自引用關係),在這種情況下,使用':foreign_key =>:id_board'等。 – PeterWong 2010-11-10 15:10:44

相關問題