ParticipantsController#new中的NoMethodError

时间:2017-10-12 12:11:25

标签: ruby-on-rails ruby-on-rails-3

为什么会出现错误?

对于我的问题,hasen是一个适当/类似的解决方案。我可以在这里找到一些提示和技巧,但现在我被卡住了。

我们有一个课程管理系统。您可以添加新的coures,参与者和人员等。我不得不改变数据库。现在还有一个表。之前关于仅在参与者表中保存的人员的所有信息。现在,当添加新参与者时,会涉及人员表。 我们想要添加课程的新参与者。我调整了参与者控制器中的新操作,我希望以旧方式传递所有数据。旧的方式是努力增加一个新的参与者。

之前的方式是:课程> 新参与者表格

现在是:课程> 搜索某个人以> 新参与者表单

的形式使用它

我认为(接受更好的方法)我只是调整旧代码?!以下是我的尝试。

错误

  参与者控件中的

NoMethodError #new 未定义的方法`参与者' for []:Array

发生。

以下是旧班级:

模型课程

Date        |    Quantity
10-09-2016  |    1
11-09-2016  |    2
12-09-2016  |    0
13-09-2016  |    0
14-09-2016  |    0
15-09-2016  |    0
16-09-2016  |    1
17-09-2016  |    0
18-09-2016  |    0
19-09-2016  |    0
20-09-2016  |    2

模特参与者

let str = "Hello, playground"
let newSTR1 = str.dropLast(3)
print(newSTR1) 

output: "Hello, playgro"

//---------------//

let str = "Hello, playground"
let newSTR2 = str.dropFirst(2)
print(newSTR2)

output: "llo, playground"

ParticipantsController

class Course < ActiveRecord::Base
  has_many :participants

当你在下面看到课程视图片段时,会有表格的新旧路径。请注意,人员搜索现在位于课程和新参与者表单之间。

class Participant < ActiveRecord::Base
  belongs_to :course
  belongs_to :organization
  belongs_to :function

以下是新课程

class ParticipantsController < ApplicationController

....
 def new
    @course = Course.find(params[:course_id])
    @participant = @course.participants.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @participant }
    end
  end

 def create
    @course = Course.find(params[:course_id])
    @participant = @course.participants.new(params[:participant])
    @course.updated_by = current_user.cn
    @course.send(:create_version)
    @course.tag_version(t(:participant_added))
    @course.save!

    respond_to do |format|
      if @participant.save
        format.html { redirect_to course_path(@participant.course), notice: 'Participant was successfully created.' }
        format.json { render json: @participant, status: :created, location: @participant }
      else
        format.html { render action: "new" }
        format.json { render json: @participant.errors, status:     :unprocessable_entity }
      end
    end
  end

以下是ParticipantsController中的调整。我的想法可能很天真,因为我还在铁轨上学习红宝石。

**old**    <%= link_to t(:add), new_course_participant_path(@course) %>

**new**    <%= link_to t(:add), course_persons_path(@course, @person)%>

提前致谢

1 个答案:

答案 0 :(得分:0)

重写:

@person = Person.find(params[:person_id])
@participant = Participant.find_by_person_id(params[:person_id])
@course= Course.find(:all, :conditions => {:id => @participant})
@participant = @course.participants.build

要:

@person = Person.find(params[:person_id])
@course = Participant.find_by_person_id(params[:person_id]).course
@participant = @course.participants.build

如果Participant.find_by_person_id(params[:person_id])返回nil

,请注意例外情况