Ruby on rails 3 Rails 3:如何将新主题与论坛关联
我正在尝试用RubyonRails编写一个论坛 在模型方面,我完成了主题和论坛之间的关联Ruby on rails 3 Rails 3:如何将新主题与论坛关联,ruby-on-rails-3,associations,Ruby On Rails 3,Associations,我正在尝试用RubyonRails编写一个论坛 在模型方面,我完成了主题和论坛之间的关联 # forum.rb class Forum < ActiveRecord::Base has_many :topics attr_accessible :name, :description end # topic.rb class Topic < ActiveRecord::Base has_many :posts belongs_to :forum end #foru
# forum.rb
class Forum < ActiveRecord::Base
has_many :topics
attr_accessible :name, :description
end
# topic.rb
class Topic < ActiveRecord::Base
has_many :posts
belongs_to :forum
end
#forum.rb
类论坛
论坛管理员
# forums_controller.rb
class ForumsController < ApplicationController
def new
@forum = Forum.new
end
def create
@forum = Forum.new(params[:forum])
if @forum.save
flash[:success] = "Success!"
redirect_to @forum
else
render 'new'
end
end
def index
@forums = Forum.all
end
def show
@forum = Forum.find(params[:id])
end
end
#forums_controller.rb
类ForumsController<应用程序控制器
def新
@forum=forum.new
结束
def创建
@论坛=论坛。新建(参数[:论坛])
如果@forum.save
flash[:success]=“成功!”
将_重定向到@forum
其他的
呈现“新”
结束
结束
def索引
@论坛=Forum.all
结束
def秀
@forum=forum.find(参数[:id])
结束
结束
主题控制器
class TopicsController < ApplicationController
def new
@topic = current_forum???.topics.build
end
def create
@topic = Topic.new(params[:topic])
if @topic.save
flash[:success] = "Success!"
redirect_to @topic
else
render 'new'
end
end
def index
@topics = Topic.all
end
def show
@topic = Topic.find(params[:id])
end
end
class TopicsController
如何更改主题的new
和create
\u controller以确保主题是为当前论坛而不是其他论坛创建的
例如,如果我从id=1的论坛创建一个新主题,我如何确保创建的新主题的论坛id=1
class TopicsController < ApplicationController
def new
@forum = Forum.find(params[:id])
@topic = @forum.topics.build
end
def新
@forum=forum.find(参数[:id])
@topic=@forum.topics.build
结束
类TopicsController
使用
您将有一条类似的路径
/forums/:forum_id/topics/new
然后在您的TopicsController
def new
@forum = Forum.find(params[:forum_id])
@topic = @forum.topics.build
end
使用
您将有一条类似的路径
/forums/:forum_id/topics/new
然后在您的TopicsController
def new
@forum = Forum.find(params[:forum_id])
@topic = @forum.topics.build
end
这似乎与我正在寻找的非常相似。要从论坛的
show
页面创建指向new
主题页面的链接,我可以这样做吗<代码>这将是新论坛\主题\路径
。用于列出您的路线。这似乎与我正在寻找的非常相似。要从论坛的show
页面创建指向new
主题页面的链接,我可以这样做吗<代码>这将是新论坛\主题\路径
。用于列出您的路线。