【问题标题】:Rails 3: How to associate a new Topic with a ForumRails 3:如何将新主题与论坛相关联
【发布时间】:2012-06-06 08:11:44
【问题描述】:

我正在尝试使用 Ruby on Rails 编写一个论坛。

在模型方面,我完成了主题和论坛的关联

# 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

论坛控制器

# 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

主题控制器

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

如何更改 topic_controller 的 newcreate 以确保该主题是为当前论坛而不是其他论坛创建的?

例如,如果我从一个 id=1 的论坛创建一个新主题,我如何确保创建的新主题的 forum_id=1?

【问题讨论】:

    标签: ruby-on-rails-3 associations


    【解决方案1】:

    使用nested resources

    resources :forums do
      resources :topics
    end
    

    你会有一条类似的路径

    /forums/:forum_id/topics/new
    

    然后在你的TopicsController

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

    【讨论】:

    • 这似乎与我正在寻找的非常相似。要从论坛的show 页面创建指向new 主题页面的链接,我可以这样做吗? &lt;%= link_to "New Topic", forum_topic_new_path %&gt;
    • 那就是new_forum_topic_path。使用rake routes 列出您的路线。
    【解决方案2】:
    class TopicsController < ApplicationController
      def new
        @forum = Forum.find(params[:id])
        @topic = @forum.topics.build
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多