2015-06-21 3 views
0

Я пытаюсь отобразить частичное в приложении rails.Оказание частичного в Rails - вложенных объектах

Я сделал это успешно с другими частицами, но разница между тем, что сработала, и это то, что это частичное принадлежит к вложенной модели. Он вложен в представление модели, которую я пытаюсь использовать для рендеринга частичного.

У меня есть две модели, Project и Project_question.

Проект имеет много проектных вопросов и принимает вложенные атрибуты для проекта.

Вопрос проекта относится к проекту.

Мои маршруты:

resources :projects do 
    resources :project_questions do 
     resources :project_answers 
    end 
    end 

Мой проект Контроллер вопрос имеет:

class ProjectQuestionsController < ApplicationController 
    before_action :set_project_question, only: [:show, :edit, :update, :destroy] 

    # GET /project_questions 
    # GET /project_questions.json 
    def index 
    @project_questions = ProjectQuestion.all 
    end 

    # GET /project_questions/1 
    # GET /project_questions/1.json 
    def show 


    end 

    # GET /project_questions/new 
    def new 
    @project_question = ProjectQuestion.new 
    @project = Project.find(params[:project_id]) 
    # @project_id = params[:project_id] 
    @project_question.project_answers[0] = ProjectAnswer.new 

    end 

    # GET /project_questions/1/edit 
    def edit 
    end 

    # POST /project_questions 
    # POST /project_questions.json 
    def create 
    @project_question = ProjectQuestion.new(project_question_params) 
    @project_question.project_id = project_question_params[:project_id] 


    respond_to do |format| 
     if @project_question.save 
     format.html { redirect_to project_url(Project.find(project_question_params[:project_id])), notice: 'Project question was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @project_question } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @project_question.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

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

    # DELETE /project_questions/1 
    # DELETE /project_questions/1.json 
    def destroy 
    @project_question.destroy 
    respond_to do |format| 
     format.html { redirect_to project_questions_url } 
     format.json { head :no_content } 
    end 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 
    def project_question_params 
     params[:project_question].permit(:id, :title, :content, :project_id, :user_id, 
     project_answer_atttibutes: [:id, :answer, :project_question_id, :user_id] 
    ) 
    end 
end 

Мой проект Форма вопрос имеет:

<%= simple_form_for [@project, @project_question] do |f| %> 
      <%= f.input :project_id, as: :hidden, input_html: {value: @project.id} %> 
      <%= f.input :title, label: 'Question:', :label_html => {:class => 'question-title'}, placeholder: 'Type your question here', :input_html => {:style => 'width: 100%', :rows => 4, class: 'response-project'} %> 
      <%= f.input :content, label: 'Is there any context or other information?', :label_html => {:class => 'question-title'}, placeholder: 'Context might help to answer your question', :input_html => {:style => 'width: 100%', :rows => 5, class: 'response-project'} %> 

    <br><br><br> 
     <%= f.button :submit, 'Send!', :class => "cpb" %> 

Мой проект Вопрос парциальное имеет:

</div> 
    <div class="generaltext"> 
    <%= @project.project_question.try(:content) %> 
    </div> 

Внутри моего проекта # шоу, я стараюсь оказывать Protect вопрос частичного следующим образом:

<%= render 'project_questions/pqps' %> 

и project_questions/_pqps.html.erb файл содержит:

<div class="containerfluid"> 
    <div class="row"> 
    <div class="col-md-10 col-md-offset-1"> 
      <div class="categorytitle"> 
      <%= @project.project_question.title %> 

      </div> 
      <div class="generaltext"> 
      <%= @project.project_question.try(:content) %> 
      </div> 
      <span class="editproject"> 
      <% if current_user.id == @project.creator_id %> 
      <%= link_to 'Answer this question', new_project_question_project_answer_path(:project_quesetion_id => @project_question.id) %> 
      <% end %> 
      </span> 
    </div> 
    </div> 
</div> 

Сообщение об ошибке, которое я получаю при попытке:

undefined method `project_question' for #<Project:0x0000010d8bad40> 
+0

Можете ли вы показать нам свою модель 'project'? Я думаю, что это может быть просто опечатка, например, отсутствие «s» в '@ project.project_questions' –

ответ

0

Моя проблема заключалась в отношениях has_many между проектными и проектными вопросами. Мне пришлось сделать цикл, чтобы показать каждый вопрос.

Это работает для меня:

<% @project.project_questions.each do |singleQuestion| %> 

     <div class="categorytitle"> 
     <%= singleQuestion.title %> 

     </div> 
     <div class="generaltext"> 
     <%= singleQuestion.try(:content) %> 
     </div> 
Смежные вопросы