Rails - 传递对象的id

时间:2012-12-08 14:21:45

标签: ruby-on-rails ruby-on-rails-3 post web get

我正在使用ruby on rails创建一个留言板网站 我生成了两个支架:TopicForumTopic belongs_to Forum

当用户创建新主题时,我应该传递forum_id(一个GET var)。类似的东西:
http://example.com:3000/topics/new/1

然后,当用户提交表单时,他使用POST请求(通过隐藏的html字段?)传回forum_id。

这样做的正确方法是什么? 感谢

路线:

  resources :forums

  get "admin/index"

  resources :posts

  resources :topics

  resources :users

  match '/signup', :to => 'users#new'

  get   '/login', :to => 'sessions#new', :as => :login
  match '/auth/:provider/callback', :to => 'sessions#create'
  match '/auth/failure', :to => 'sessions#failure'

  match '/topics/new/:id', :to => 'topics#new'

1 个答案:

答案 0 :(得分:2)

这样做的好方法是将topics资源嵌套在forums资源中,如下所示:

resources :forums do
  resources :topics
end

然后在你的TopicsController

class TopicsController < ApplicationController
  def new
    @forum = Forum.find params[:forum_id]
    @topic = Topic.new
  end

  def create
    @forum = Forum.find params[:forum_id] # See the redundancy? Consider using before_filters
    @topic = @forum.topics.build params[:topic]

    if @topic.save
      redirect_to @topic
    else
      render action: :new
    end
  end
end

最后在你的views / topics / _form.html.erb中:

<%= form_for [@forum, @topic] do |f| %>
  # Your fields
<% end %>