我该如何解决这个问题?
我有2个按钮: /views/subjects/_inscription_button.html.haml
- if subject.participation(current_participant).nil?
= link_to "Ca m'intéresse !", subject_participant_index_path(:interested_id => current_participant.id, :subject_id => subject.id), remote: true, :method => :post, class:"btn btn-primary"
- else
= link_to "Ca ne m'intéresse plus !", delete_participation_path(@subject.participation(current_participant).id),:method => :delete, remote: true, class:"btn btn-primary"
第二个link_to
并不想正常切换。我收到错误:
/ subject_participant / 115的NoMethodError 未定义的方法`id'为零:NilClass
实例变量subject
适用于第一个按钮但不适用于第二个按钮...
以下是其他有用的代码: subject_participant_controller.rb:
class SubjectParticipantController < ApplicationController
before_action :authenticate_participant!
def create
@subject = Subject.find(params[:subject_id])
@subject_participant = SubjectParticipant.new(subject_participant_params)
if @subject_participant.save
respond_to do | format |
format.html {redirect_to subjects_path}
format.js
end
else
redirect_to subjects_path
end
end
def destroy
@subject_participant = SubjectParticipant.find(params[:id])
if @subject_participant.destroy
respond_to do | format |
format.html {redirect_to subjects_path}
format.js
end
else
redirect_to subjects_path
end
end
def subject_participant_params
params.permit(:interested_id, :subject_id, :id)
end
end
/routes.rb:
Rails.application.routes.draw do
devise_for :participants
resources :subjects
resources :participants
resources :conferences
resources :subject_participant
delete 'subject_participant/:id' => 'subject_participant#destroy', as: 'delete_participation'
root 'welcome#index'
subject.rb中
class Subject < ActiveRecord::Base
validates_presence_of :title, :questioner, :conference, :description
has_many :subject_participants
has_many :interested, through: :subject_participants #interested
belongs_to :questioner, class_name: "Participant"
belongs_to :conference
def participation(current_participant)
self.subject_participants.find_by_interested_id(current_participant.id)
end
end
答案 0 :(得分:1)
它告诉你@subject.participation(current_participant)
是零。你需要解决它。
请记住,在Rails视图中使用实例变量时,需要在相应的控制器操作中定义它们。从您的部分向后退到其父视图。它与哪种控制器动作有关?
您可以在此处定义部分所需的实例变量。
答案 1 :(得分:0)
只需用户@subject代替主题。
- if subject.participation(current_participant).nil?
= link_to "Ca m'intéresse !",subject_participant_index_path(:interested_id => current_participant.id, :subject_id => @subject.id), remote: true, :method => :post, class:"btn btn-primary"
- else
= link_to "Ca ne m'intéresse plus !", delete_participation_path(@subject.participation(current_participant).id),:method => :delete, remote: true, class:"btn btn-primary"