如果 TOPIC 属于 USER 和 FORUM,我想知道 TOPIC 的new
andcreate
方法应该是什么样子。
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
TOPIC只属于FORUM的时候,我利用了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
返回当前用户对象。