2014-08-28 9 views
0

단계별 지침을 표시 할 사이트를 만들려고합니다. 사용자가 질문을보고 대답을 선택합니다. 대답보기는 다음과 같습니다.레일 : 생성 후 개체 연결

<p id="notice"><%= notice %></p> 

<p> 
    <strong>Post:</strong> 
    <%= @question.post %> 
</p> 

<%= link_to 'Answer', new_step_path(:question_id=>@question.id) %> | 
<%= link_to 'Edit', edit_question_path(@question) %> | 
<%= link_to 'Back', questions_path %> 

사용자가 "대답"을 선택하면 단계 양식을 렌더링하는 # 단계로 리디렉션됩니다.

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

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

    <div class="actions"> 
    <%= @question.id %> 
    <%= f.hidden_field :question_id, :value => @question.id %> 
    </div> 

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

관련 질문을 URL에서 숨겨진 필드로 전달합니다.

단계 has_many : questions, : through => : instruction을 사용하면 단계 컨트롤러가 단계를 생성 한 후 지침 모델에 숨겨진 필드 값을 삽입하는 방법은 무엇입니까?

class StepsController < ApplicationController 
    before_action :set_step, only: [:show, :edit, :update, :destroy] 

    # GET /steps 
    # GET /steps.json 
    def index 
    @steps = Step.all 
    end 

    # GET /steps/1 
    # GET /steps/1.json 
    def show 
    end 

    # GET /steps/new 
    def new 
    @step = Step.new 
    @question = Question.find(params[:question_id]) 
    end 

    # GET /steps/1/edit 
    def edit 
    end 

    # POST /steps 
    # POST /steps.json 
    def create 
    @step = Step.new(step_params) 

    respond_to do |format| 
     if @step.save 
     @instruction = Instruction.create(:question_id=>@question, :step_id=>@step, :order=>1) 

     format.html { redirect_to @step, notice: 'Step was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @step } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @step.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

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

    # DELETE /steps/1 
    # DELETE /steps/1.json 
    def destroy 
    @step.destroy 
    respond_to do |format| 
     format.html { redirect_to steps_url } 
     format.json { head :no_content } 
    end 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 
    def step_params 
     params.require(:step).permit(:post) 
    end 
end 
+0

"어떻게 숨겨진 필드 값을 지침 모델에 삽입합니까?" 모델과보기를 게시 할 수 있습니까? 나는 당신이 찾고있는 것이 무엇인지 확실하게 분명히 추측합니다. –

+0

기본적으로 지침은 단계 및 질문과 관련이 있습니다. 질문에 대답 할 때 첫 번째 단계가 만들어진 후에 지침을 작성하려고합니다. 문제는 단계 # new에서 단계 # create로 질문 번호를 전달할 수있는 방법입니다. – jstein

답변

1

나는 여전히 세 가지 모델이 서로 관련이 있는지 분명하지 않다 모델의 관계에 대해 물었다 있지만 (만 언급 : 단계 has_many : 질문 : 명령 =>를 통해). 어쨌든 나는 내 가정에 근거하여 당신의 질문에 답합니다.
모델 : 그래서 조심

class Step < ActiveRecord::Base 
    belongs_to :instruction 
    has_many :questions, 
    through: :instruction 
end 

class Instruction < ActiveRecord::Base 
    has_many :steps 
    has_many :questions 
end 

class Question < ActiveRecord::Base 
    belongs_to :instruction 
end 

지금 당신의 steps_controller.rb : 코드에서 @question 인스턴스화 여기서 모든
먼저?

@instruction = Instruction.create(:question_id=>@question, :step_id=>@step, :order=>1) 

그 라인은보기의 REST 관점에서 매우 혼란 :
왜 #가 만든 StepsController는 명령을 작성해야합니까?
다른 방법으로 처리 할 수없는 경우 Step 모델 콜백에 넣으십시오. 당신은보기
의 트랜잭션 관점에서 또한 그것을 원할 것입니다, 당신의 행동이 더 같이해야하는 이유
가 있다고) :

def create 
    @step = Step.new(step_params) 
    respond_to do |format| 
    if @step.save 
     format.html { redirect_to @step, notice: 'Step was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @step } 
    else 
     format.html { render action: 'new' } 
     format.json { render json: @step.errors, status: :unprocessable_entity } 
    end 
    end 
end 

때문에 단계 모델 :

class Step < ActiveRecord::Base 
    belongs_to :instruction 
    has_many :questions, 
    through: :instruction 
    attr_accessor :question_id 
    before_create :create_related_instruction 

    private 
    def create_related_instruction 
    self.create_instruction question_id: question_id, order: 1 
    end 
end 

난 당신이 아이디어를 얻을 생각 .

+0

감사합니다. 이것은 많은 의미를가집니다 (그리고 여러분의 가정은 정확합니다). 일단 내가 이것을 시도하면 작동한다면 이것을 받아 들일 것입니다. – jstein

+0

"개인"을 제거하지 않으면 NoMethod 오류가 발생합니다. 이 사이트가 손상 될 수 있습니까? question_id는 어디에 할당합니까? Step # new에서 할당하면 저장하지 않고 Step # create를 지정하면 "ID없이 질문을 찾을 수 없습니다."라는 메시지가 나타납니다. – jstein

+0

죄송합니다. 오타가 있습니다 : 개인 콜백 메소드 이름이 변경되었습니다. question_id의 측면에서 보면, 양식에서 나온 것입니다. 이미 새로운 단계로 게시했습니다. 게다가 나는 건축 문제가 있다고 강력히 믿는다. 단계가 생성 된 후에 지침이 생성되어야하는 이유는 질문이 이미 존재하는 이유는 무엇입니까? 어쨌든 나는 대상과 그 관계에 대해 다시 한번 생각해보기를 강력하게 권장합니다. 또한 잠재 고객에게 도움이 필요하면 #reenvillon 레일즈에서 나를 만날 수 있습니다. –