当前位置: 动力学知识库 > 问答 > 编程问答 >

activerecord - rails active record object in application controller

问题描述:

I'm adding a site-wide form for asking questions on a rails site. The models/views/controllers for the resource question are already created. Going to question/new shows the form as you'd expect. Now I want to display a site-wide question form (the only difference with this one is that it only shows mandatory fields). Question: should I create a new question object in application_controller and pass that to the rails form_for helper, or should I create a new _form2 partial(in the question view) and just include that in my site-wide template?

Thank you.

网友答案:

Create a question_form partial in the views/shared folder, and reference that from the site wide template.

Edit: in reply to where to get the @question variable from

You have two options in my mind, you can load the variable in ApplicationController:

class ApplicationController < ActionController::Base

  before_filter :load_question

  def load_question
    @question = Question.new
  end

  ...

end

(You should be careful of conflicts with the @question variable in this case)

Or probably better, you can create a method in ApplicationHelper:

module ApplicationHelper

  def question_form

    question = Question.new

    raw render 'shared/question_form', :question => question
  end

  ...
end

Then in your view, instead of referencing the partial, you reference the helper:

<%= question_form %>

In this case you would need to reference the variable in the partial as a local variable, so question instead of @question.

Hope that helps.

分享给朋友:
您可能感兴趣的文章:
随机阅读: