Rails - linking to parent associations

≯℡__Kan透↙ 提交于 2019-12-25 03:45:11

问题


I'm trying to make an app with Rails 4.

I have a project.rb and a project_student_eoi.rb.

The associations are:

project has many project student eons
project student eois belong to project

On my project show page, I have a link to a form where students can express interest in joining a project.

<% if can? :read, Project && current_user.profile.has_role?(:student) %>
          <%= link_to  'Join this project', new_project_student_eoi_path %>
        <% end %>

Then on the new page (which nests the form), I have a back link, which should go back to the project itself. The scaffolding structure goes back to an index of all the project student eois. I'm trying to change this so that the path goes back to the project.

I've tried all of these variations and am not getting anywhere. I'm struggling with associations generally. My project student eoi table has an attribute called :project_id. I want to use that to match up to the project which is being used to send the link to the new expression of interest form.

  <h1 class="header-project" style="margin-bottom:10%">
    Express your interest in this project
  </h1>


  <%= render 'form' %>


<div class="formminor">
    <%= link_to 'Back', project_path(:project_id => project.id) %>

I have also tried:

<%= link_to 'Back', project_path(:project_id => :project.id) %>
<%= link_to 'Back', project_path(project_id: @project.id) %>
<%= link_to 'Back', project_path(project_id: => project.id) %>

and several other variations - how do you do this?


回答1:


You need to pass "project_id" param on "Join This Project"

app/views/projects/show.html.erb

<% if can? :read, Project && current_user.profile.has_role?(:student) %>
    <%= link_to  'Join this project', new_project_student_eoi_path(project_id: @project.id) %>
<% end %>

and then make sure project_id attribute is set on "new" action

app/controllers/projects/project_student_eois_controller.rb

class ProjectStudentEoisController < ApplicationController
  def new
    @project_student_eoi = ProjecStudentEoi.new(project_id: params[:project_id])
  end
end

once project_id is set, you can use this :

<%= link_to 'Back', project_path(@project_student_eoi.project) %>


来源:https://stackoverflow.com/questions/33060266/rails-linking-to-parent-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!