2015-06-19 2 views
1

Я пытаюсь выяснить, рельсы 4.Rails 4 - Путь

У меня есть модель проекта и модель project_question.

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

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

В моей project_question_form у меня есть:

<div class="containerfluid"> 
    <div class="row"> 
    <div class="col-md-10 col-md-offset-1"> 

     <div class="header-project">What would you like to know?</div> 

     <%= render 'form' %> 
     <div class="formminor"> 
     <%= link_to 'Back', projects_path(@project) %> 
     </div> 
    </div> 
    </div> 
</div> 

Я ожидаю, что квадратные скобки бит в «Назад» ссылку, чтобы вернуться на страницу проекта, что пользователь был когда они нажали «задать вопрос». Вместо этого пользователь возвращается на страницу с указанием индекса всех проектов.

В моей задать форму вопроса, у меня есть:

<div class="containerfluid"> 
    <div class="row"> 
    <div class="col-md-10 col-md-offset-1"> 
     <%= simple_form_for :project_questions do |f| %> 
       <%= f.input :project_id, as: :hidden, input_html: {value: @project_question_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" %> 

    <% end %> 
    </div> 
    </div> 
</div> 

В моем routes.rb, у меня есть:

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

Может кто-нибудь увидеть, что я сделал не так? Я попытался использовать (@project_id) и (@ project.id) вместо (@project) в первом виде. Ни одна из этих альтернатив не работает.

Мой projects_controller имеет:

class ProjectsController < ApplicationController 
    #layout :projects_student_layout 

    before_action :authenticate_user! 

    # GET /projects 
    # GET /projects.json 
    def index 
    @projects = current_user.projects 


    #can i have more than one index? do i need to change something in the routes? if i want to list the related projects and the expiring projects - how do i do that within one index? 

    #is there a way to order these, so that for educators they are in order of course and for students they are in order of next milestone date? 
    #@projects.order("created_at DESC") 
    end 

    # def index2 
# @projects = Project.find_xxx_xx 
# end 

    def list 
    @projects = Project.find(:all) 
    end 

    def toggle_draft 
    @project = Project.find(params[:id]) 
    @project.draft = true 
    @project.save 
    redirect_to project_path(@project) 
    end 

    # GET /projects/1 
    # GET /projects/1.json 
    def show 
    #authorise @project 

    @project = Project.find(params[:id]) 
    @creator = User.find(@project.creator_id) 
    @creator_profile = @creator.profile 

    #@approver_profile = User.find(@project.educator_id).profile #educators are the only people who approve projects 
# if profile == 'studnet' 
    #@approval = @project.approval 

# @invitations = @project.project_invitations 

    end 

    # GET /projects/new 
    def new 
    #authorise @project 
    @project = Project.new 
    @project.scope = Scope.new 
    @project.scope.datum = Datum.new 
    @project.scope.material = Material.new 
    @project.scope.mentoring = Mentoring.new 
    @project.scope.participant = Participant.new 
    @project.scope.funding = Funding.new 
    @project.scope.ethic = Ethic.new 
    @project.scope.group_research = GroupResearch.new 
    @project.scope.backgroundip = Backgroundip.new 
    @project.scope.result = Result.new 
    @project.scope.finalise = Finalise.new 

    end 

    # GET /projects/1/edit 
    def edit 
    #authorise @project 
    @project =Project.find(params[:id])  
    end 

    # POST /projects 
    # POST /projects.json 
    def create 
    #authorise @project 
    @project = Project.new(project_params) 
    @project.creator_id = current_user.id 
    @project.users << current_user 
    respond_to do |format| 
     if @project.save 
     format.html { redirect_to @project }, flash[:notice] = "Project saved" 
     format.json { render action: 'show', status: :created, location: @project } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @project.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /projects/1 
    # PATCH/PUT /projects/1.json 
    def update 
    #authorise @project 
    @project = Project.find(params[:id]) 
    @project.creator_id = current_user.id 

    respond_to do |format| 
     if @project.update(project_params) 
     format.html { redirect_to @project } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @project.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /projects/1 
    # DELETE /projects/1.json 
    def destroy 
    #authorise @project 

    @project.destroy 
    respond_to do |format| 
     format.html { redirect_to projects_url } 
     format.json { head :no_content } 
    end 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 

    def project_params 
     params.require(:project).permit(
     :id, :title, :description, :video_proposal, :link_to_video_proposal, 
     :expiry_date_for_sponsor_interest, :motivation, :approach, 
     :completion_date, :start_date, :industry_id, :recurring_project, 
     :frequency, :date_for_student_invitation, :date_for_student_interest, :closed, :student_objective, 
     :industry_relevance, :hero_image, :project_id, 
     project_question_attributes: [:title, :content, :user_id, :project_id, 
     project_answer_attributes: [:answer, :project_question_id]], 
     scope_attributes: [:id, :project_id, :data, :material, :mentoring, :participant, :funding, :ethic, :group, :result, :disclosure, :finalise, 
         :if_mentoring, :if_participant, :if_funding, :if_ethic, :if_group_research, :if_backgroundip, :if_datum, :if_material, 
         datum_attributes: [:id, :prim_sec, :qual_quant, :survey, :survey_link, :experiment, :other_type, :other_description, 
              :confidential, :data_description, :scope_id], 
         material_attributes: [:id, :mattype, :description, :scope_id], 
         mentoring_attributes: [:id, :frequency, :description, :scope_id], 
         funding_attributes: [:id, :expenses, :honorarium, :financing, :currency, :size, :amount_expenses, :amount_honorarium, 
           :comment, :amount_principal_financing, :return_on_finance, :period_of_return, :expense_description, :amount_expenses_pennies, :amount_honorarium_pennies, :amount_principal_financing_pennies, 
               :amount_expenses_currency, :scope_id], 
         participant_attributes: [:id, :title, :description, :location, :costs, :participation_cost, 
                :eligibility, :eligibility_criteria, :currency, :participation_cost_pennies, :participation_cost_currency, 
                :location_specific ], 
         group_research_attributes: [:id, :number_of_group_members, :scope_id], 
         ethic_attributes: [:id, :obtained, :date_expected, :ethics_comment, :ethics_policy_link, :scope_id], 
         result_attributes: [:id, :report, :standard_licence, :bespoke_licence, :option, :assignment, :other_outcome, 
              :consulting, :link_to_bespoke_licence, :description], 
         disclosure_attributes: [:id, :allusers, :publicity, :limitedorganisation, :limitedindustry, :limiteduser, :approveddisclosure], 
         backgroundip_attributes: [:id, :scope_id, :copyright, :design, :patent, :trademark, :geographical_indication, 
                :trade_secret, :other, :identifier_copyright, :identifier_design, :identifier_patent, 
                :identifier_trademark, :identifier_geographical_indication, :identifier_trade_secret, 
                :identifier_other, :description, :registered_owner, :unregistered_interest, :conditions, 
                :pbr, :identifier_pbr ], 

         finalise_attributes: [:id, :draft, :reminder, :reminder_date, :finalised_at, :scope_id] 
          ] 
    ) 


    end 

Когда я расслоение EXEC рек маршрутов (как предложено ниже), я получаю много маршрутов для всех моделей. Те, которые включают в себя project_question являются:

project_answers#destroy 
        project_project_questions GET  /projects/:project_id/project_questions(.:format)            project_questions#index 
               POST  /projects/:project_id/project_questions(.:format)            project_questions#create 
       new_project_project_question GET  /projects/:project_id/project_questions/new(.:format)           project_questions#new 
       edit_project_project_question GET  /projects/:project_id/project_questions/:id/edit(.:format)          project_questions#edit 
        project_project_question GET  /projects/:project_id/project_questions/:id(.:format)           project_questions#show 
               PATCH /projects/:project_id/project_questions/:id(.:format)           project_questions#update 
               PUT  /projects/:project_id/project_questions/:id(.:format)           project_questions#update 
               DELETE /projects/:project_id/project_questions/:id(.:format)           project_questions#destroy 

маршрут предложение Чада:

projects GET  /projects(.:format)                    projects#index 
               POST  /projects(.:format)                    projects#create 
            new_project GET  /projects/new(.:format)                   projects#new 
           edit_project GET  /projects/:id/edit(.:format)                 projects#edit 
             project GET  /projects/:id(.:format)                   projects#show 
               PATCH /projects/:id(.:format)                   projects#update 
               PUT  /projects/:id(.:format)                   projects#update 
               DELETE /projects/:id(.:format)                   projects#destroy 

Мой project_question контроллер:

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_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_question, 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 

Эта ссылка находится в моих проектах показать страницу:

<%= link_to 'Ask a question', new_project_project_question_path(:project_id => @project.id) %> <% end %> 
+0

пожалуйста показать свои проекты контроллера. Я считаю, что вы не определили '@ project' – gabrielhilal

+0

Pavan - мои проекты_contorller размещены. Вы также предлагаете опубликовать контроллер project_question? – Mel

+0

С какого действия контроллера вы вызываете 'project_question_form'? – Pavan

ответ

0

Во-первых, попробуйте:

project_path(@project_id) 

Тогда, если это не сработает, то вам необходимо убедиться, что при переходе со страницы проекта на задайте страницу вопросов, вы передаете @project.id в качестве параметра, называемого project_id.

+0

Привет, Чад, как узнать, показывает ли он правильный маршрут? URL-адрес браузера показывает идентификатор проекта, когда я нахожусь в форме вопроса. Я не знаю, как проверить, является ли project.nil? == true или где попробовать. Я знаю, что проект сохранен, потому что я проверял его на консоли. – Mel

+0

Я пробовал рейк-маршруты | grep projects_path, но он не давал никаких результатов, я пробовал его без _path, и я получил результат, который я вставил в вопрос – Mel

+0

ОК, так что это означает, что вы не получаете фактический маршрут при вызове 'projects_path'. Думаю, вы должны называть 'project_path', но тогда вам нужно передать ему идентификатор. Вам нужно будет проверить, есть ли '@ project.nil?' И использовать только «project_path (@project)», если он присутствует.Если он всегда должен быть там, но нет, это тоже часть вашей проблемы. –

0

You sh ould использовать project_path(@project) вместо projects_path(@project).

+0

Спасибо в любом случае Yogesh, но когда я попробую это, я получаю эту ошибку: никаких совпадений маршрутов {: id => nil} отсутствуют необходимые ключи: [: id ] Неправильно – Mel

+0

Итак, как вы определяете свои маршруты? –

0

Самое лучшее, что я хотел бы предложить запустить bundle exec rake routes

Затем получить определяют ваше имя пути и необходимые параметры. Исходя из вашей проблемы, мы не можем правильно ответить на правильный путь. Поэтому наилучшей практикой является использование рейк-маршрутов.

+0

Как определить свой путь? – Mel

+0

, как я ответил, когда вы запускаете рейк-маршруты на своем терминале, вы увидите список доступных маршрутов в отношении своего контроллера и действия. И будет список требуемых имен параметров. – Rubyrider

+0

Что мне делать с выходом этой функции? Я скопировал бит рейк-маршрутов на вопрос выше. Могу ли я скопировать все эти ссылки на ссылку «назад»? – Mel

0

Не могли бы вы попробовать

project_path(@project_question_id) 
+0

Спасибо Sebi. Я боюсь, что также возвращается к индексу всех проектов (чего я вообще не понимаю). Спасибо, в любом случае, я пытаюсь найти способ отправить его обратно на саму страницу проекта. – Mel

0

Вы должны определить @project в вашем new действия вашей ProjectQuestionsController ниже

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

и изменить link_to в

<%= link_to 'Back', project_path(@project) %> 
+0

Является ли вторая строка нового действия вместо этой строки: @project_id = params [: project_id] – Mel

+0

@ user2860931 Да. – Pavan

+0

Я не понимаю, что делает кто-то из них - что-то не так с тем, как у меня есть с предложением Чада? – Mel

Смежные вопросы