开发者

Passing parent resource id to a create action from a form

开发者 https://www.devze.com 2023-02-07 05:56 出处:网络
I开发者_Python百科 have a Forum that has many Topics. My routes are the following: GET/forums/:forum_id/topics/new => Topics#new

I开发者_Python百科 have a Forum that has many Topics. My routes are the following:

GET  /forums/:forum_id/topics/new => Topics#new
POST /topics                      => Topics#create

This is where my problem starts:

= form_for @topic do |topic_form|

This form maps to the POST /topics route. A forum_id has to be provided in order to save the topic. It is available to the new action, but I can't find any way to pass it to the create action.

I tried changing the routes to:

GET  /forums/:forum_id/topics/new => Topics#new
POST /forums/:forum_id/topics     => Topics#create

But now the forum_id ended up outside the topic parameter hash:

{ topic: { title: "Test" }, commit: "Create Topic", forum_id: 1 }

How do I solve this problem?


I think the most proper way is to route it like you did in the second example. And then in the create action you can first instantiate the forum to make sure it is valid and then create a topic from the forum. It could look something like this:

def create
  @forum = Forum.find(params[:forum_id])
  @topic = @forum.topics.new(params[:topic])
  if @topic.save
    ...
  else
    ...
  end
end

This assumes that your Forum model has_many :topics

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号