2014-02-23 5 views
0

설문 조사에 많은 질문이있을 수있는 설문 조사 앱을 만드는 중입니다. 설문 조사에는 많은 설문 조사가있을 수 있습니다. 제가하고 싶은 것은 설문 조사 페이지에 "설문 조사 추가"버튼을 표시하여 사용자가 설문 조사에 새로운 질문을 추가 할 수있게하는 것입니다. 그래서 내 코드에서 나는이 같은 설문 조사 ID를 보내 Rails 인스턴스 변수

<%= link_to "Add Question", new_question_path(:survey_id => @survey.id)%> 

그럼 내가 내 질문 컨트롤러에 전송있어 PARAMS를 사용하여 @survey 설정할 수 있습니다. 이것은 내 : new 메소드에서 잘 작동하지만, : create 메소드를 호출하려고 할 때 nil 오류가 발생합니다. 나는 이것이 컨트롤러의 새로운 인스턴스가 생성되어 점점 더 이상 : survey_id 매개 변수에 액세스 할 수 없기 때문에 이것이라고 생각합니다.

어쨌든 매개 변수를 컨트롤러의 다음 인스턴스로 전달할 수 있는지 궁금합니다. 아니면 그 질문에 대해 설문 조사를 보내야 할 더 좋은 방법이 있습니까? 숨겨진 필드에 내가 저장할 수있는 것입니까? 내 모델에 무언가를 저장하려고 생각했지만 이전에 질문을 저장하면 내가 가진 유효성을 제거해야 할 것입니다.

class QuestionsController < ApplicationController 
    before_action :set_question, only: [:show, :edit, :update, :destroy] 
    before_action :set_survey, only: [:new, :create] 
    # GET /questions 
    # GET /questions.json 
    def index 
    @questions = Question.all 
    end 

    # GET /questions/1 
    # GET /questions/1.json 
    def show 
    @answers = @question.answers 
    end 

    # GET /questions/new 
    def new 
    @question = Question.new 
    end 

    # GET /questions/1/edit 
    def edit 
    end 

    # POST /questions 
    # POST /questions.json 
    def create 
    @question = Question.new(question_params) 

    respond_to do |format| 
     if @question.save 
     @survey.questions << @question 
     format.html { redirect_to @question, notice: 'Question was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @question } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @question.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /questions/1 
    # PATCH/PUT /questions/1.json 
    def update 
    respond_to do |format| 
     if @question.update(question_params) 
     format.html { redirect_to @question, notice: 'Question was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @question.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /questions/1 
    # DELETE /questions/1.json 
    def destroy 
    @question.destroy 
    respond_to do |format| 
     format.html { redirect_to questions_url } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_question 
     @question = Question.find(params[:id]) 
    end 

    def set_survey 
     @survey = Survey.find(params[:survey_id]) 
     flash[:alert] = "Survey is " + @survey.to_s 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def question_params 
     params.require(:question).permit(:title, :single_response, :surveys, :surveytizations) 
    end 
end 

그리고 내가 함께 질문을 만드는거야 형태 :

<%= form_for(@question) do |f| %> 
    <% if @question.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2> 

     <ul> 
     <% @question.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </div> 
    <div class="field"> 
    <%= f.label :single_response %><br> 
    <%= f.check_box :single_response %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

감사

여기 내 question_controller입니다! 어떤 도움이라도 대단히 감사합니다!

UPDATE :

내가 Rails.cache.write/Rails.cache.read 사용하여 작업 할 수 있었다 - 아무것도 그런 식으로 일을 잘못 있는가 또는 최적의 경로이다 How to pass values between controller methods

?

+0

중첩 된 경로를 사용하는 것이 가장 좋습니다. 캐시는 임시이므로 캐시가 플러시되는 경우 여전히 nil의 가능성이 있습니다. 그리고 캐시하는 방법에 따라 다른 사용자가 잘못된 설문 ID를 얻을 수 있습니다. – sonnyhe2002

+0

처음에는 조사> 질문을 위해 중첩 된 경로를 사용했지만 질문을 중첩 할 때 많은 문제가 발생하기 시작했습니다. 더블 중첩 경로/양식을 처리하는 방법에 대한 좋은 자습서 또는 리소스에 대해 알지 못합니까? –

+0

답을 얻으려면 이중 중첩 경로가 필요하지 않으므로 두 개의 질문 자원, 즉 설문 중첩 된 질문과 그렇지 않은 질문을 정의 할 수 있습니다. 그렇지 않은 사람은 여전히 ​​대답을위한 자원을 보유 할 것입니다. – sonnyhe2002

답변

1

난 당신이 숨겨진 필드에 survey_id 저장할 필요가 있다고 생각합니다. 그런 다음 질문 컨트롤러에서 액세스 할 수 있습니다. 보기에서 :

<%= form_for(@question) do |f| %> 
    <%= f.hidden_field :survey_id %> 
#rest of form 

또한있을 수는 다음과 같이 뭔가에 new 작업을 변경하려면 :

@question = Question.new(:survey_id => params[:survey_id]) 

항상 설문 조사에 속한 질문이 노선 둥지에 좋은 생각이 될 수 있다면 그래서 당신은 항상 어떤 조사를하고 있는지 확인할 수 있습니다.

+0

숨겨진 필드에 추가하는 모습을 보여줄 수 있습니까? 나는 좋은 모범을 찾을 수 없었습니다. 처음에는 질문을 중첩했습니다. 하지만 그 질문들 안에 중첩 된 대답들에 문제가 생겨서 그들을 구분하기로 결정했습니다. –

+0

물론입니다!내 대답을 –

+0

업데이트했습니다 또한 사용자가 설문 조사 및 질문을 만들게한다면 survey_id가 다른 사용자의 것이 아닌지 확인하고 싶을 것입니다. –