未定义的方法 - 提交表单后属性为NULL(Rails 3.2.13)

时间:2017-10-16 14:24:09

标签: ruby-on-rails forms associations

ERROR:

undefined method 'function_id' for #<Person:0xa004934>

有一个试用管理系统。到目前为止,用户已经能够创建新的参与者。现在,用户也应该能够创建新人。那个人也是试验的参与者。

我们有一个表单来创建一个新人。在表单中点击create person后,只有人员表记录正常。但participant表中的 function_id 属性为 NULL 。当用户创建人时,在participant表中仅设置值 function_id 有什么必要?因此,当创建新人时,应始终创建参与者。

4 表:

  • trial has_many :participants
  • 参与者belongs_to
  • person has_many participants ... has_many:试用,通过:参与者
  • 函数has_many参与者

到目前为止有效:

使用表单/views/participants/new.html.erb创建新参与者(id | trial_id | function_id | person_id)。使用表单/views/persons/new.html.erb创建一个新人(id | title | prename | surname等)并不像上面提到的那样100%。 在persons/new.html.erb形式中,用户应该能够在下拉框中选择一个选项,该选项是participant的功能。

我不想要一个完整的新participant记录。我只想要 function_id 值。

以下是/persons/views/new.html.erb

的摘要
<%= form_for([@trial, @person]) do |f| %>
<div class="table">
<fieldset>
  <div class="table">
    <div class="tr">
      <div class="th">
        <%= f.label t(:function) %>
      </div>
      <div class="tdsep">:</div>
      <div class="td">
       <%= f.select :function_id, Function.all.collect {|fu| [fu.german, fu.id]}  %>
     </div>
    </div>
   ...

修改

人物模型

class Person < ActiveRecord::Base
  belongs_to :organization
  attr_accessible :organization_id,:title,:prename,:surname,:street,:street_number,:zip_code,:city,:phone,:fax,:email,:organization_description, :participants_attributes
  has_many :participants
  has_many :trials, through: :participants

PersonsController

class PersonsController < ApplicationController

 load_and_authorize_resource :person, :through => :trial, :only => [:destroy]
 before_filter :authenticate_user!, :except => [:index, :new, :create, :show]
 load_and_authorize_resource :trial

 def new
  @person = Person.new
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @person}
  end
end

def create
  @person = Person.new(params[:person])
  @person.trials << @trial
  respond_to do |format|
    if @person.save
      format.html { redirect_to @person, notice: 'Person was successfully created.' }
      format.json { render json: @person, status: :created, location: @person }
    else
      format.html { render action: "new" }
      format.json { render json: @person.errors, status: :unprocessable_entity }
    end
  end
end

提前致谢。

2 个答案:

答案 0 :(得分:0)

您必须将chmod()添加到您的个人模型中。

答案 1 :(得分:0)

您无法在人员新视图中添加function_id,因为人员数据库中没有function_id

因此解决方案是制作select_tag而不是f.select

 <%= select_tag :function_id, options_from_collection_for_select(Function.all.collect {|fu| [fu.german, fu.id]})  %>

有关更多信息,请参阅here