2012-06-28 11 views
0

我想知道TOPIC的newcreate方法應該是什麼樣子,如果TOPIC屬於USER和FORUM。TOPIC控制器中的新建和創建方法如果TOPIC屬於USER和FORUM

class Forum < ActiveRecord::Base 
    belongs_to :user 
    has_many :topics, :dependent => :destroy 
end 

class User < ActiveRecord::Base 
    has_many :forum 
    has_many :topic 
end 

class Topic < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :forum 
end 

當話題屬於唯一的論壇,我利用build方法是這樣的。

def new 
    @forum = Forum.find(params[:forum_id]) 
    @topic = @forum.topics.build 
end 

def create 
    @forum = Forum.find(params[:forum_id]) 
    @topic = @forum.topics.build(params[:topic]) 
    if @topic.save 
    flash[:success] = "Success!" 
    redirect_to topic_posts_path(@topic) 
    else 
    render 'new' 
    end 
end 

但是現在TOPIC屬於FORUM和USER,我不知道該怎麼辦?有關此主題的任何建議?

這是我的模式以供參考。現在忽略POST。

create_table "forums", :force => true do |t| 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.string "name" 
    t.text  "description" 
    t.integer "user_id" 
end 

create_table "posts", :force => true do |t| 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "topic_id" 
    t.text  "content" 
    t.integer "user_id" 
end 

create_table "topics", :force => true do |t| 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    t.integer "forum_id" 
    t.string "name" 
    t.integer "last_post_id" 
    t.integer "views" 
    t.integer "user_id" 
end 

create_table "users", :force => true do |t| 
    t.string "name" 
    t.string "email" 
    t.datetime "created_at",       :null => false 
    t.datetime "updated_at",       :null => false 
    t.string "password_digest" 
    t.string "remember_token" 
    t.boolean "admin",   :default => false 
end 

我的解決辦法,以新create方法

def create 
    @forum = Forum.find(params[:forum_id]) 
    @topic = @forum.topics.build(params[:topic]) 
    @topic.user_id = current_user.id 

    if @topic.save 
    flash[:success] = "Success!" 
    redirect_to topic_posts_path(@topic) 
    else 
    render 'new' 
    end 
end 

current_user返回當前用戶對象。

回答

0
topic = Topic.new 
topic.forum = Forum.first 
topic.user = User.first 

topic = Topic.create(:forum => Forum.first, :user => User.first) 

topic = @user.topics.build(params[:topic]) 
topic.forum = @forum 

etc