TOPIC が USER および FORUM に属している場合、TOPICのnew
andメソッドはどのように見えるべきか疑問に思っています。create
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
現在のユーザー オブジェクトを返します。