我正在使用带有PostGre数据库的Rails 4.2.3。我有一个有几个成员对象的对象。在我的app / models / my_object.rb文件中,我有
class MyObject < ActiveRecord::Base
belongs_to :user
has_many :my_object_times
has_one :address
attr_accessor :hour, :minute, :second
validates_numericality_of :overall_rank, :age_rank, :gender_rank
accepts_nested_attributes_for :my_object_times
end
然后在我看来,我的形式是......
<%= f.fields_for :my_object_times do |rt| %>
<div class="field">
<%= rt.label :overall_rank %><br>
<%= rt.text_field :overall_rank %>
</div>
但提交表单时出现此错误
NoMethodError (undefined method `overall_rank' for #<MyObject:0x007fd66df43968>):
app/controllers/my_objects_controller.rb:10:in `block in create'
app/controllers/my_objects_controller.rb:9:in `create'
我不明白为什么我收到这个错误。下面是我的app / controllers / my_objects_controller.rb文件
class MyObjectsController < ApplicationController
def create
@my_object = MyObject.new(my_object_params)
@current_user = User.find(session["user_id"])
@my_object.user = @current_user
@date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
@my_object.day = @date
respond_to do |format|
if @my_object.save
flash[:notice] = 'Saved successfully'
format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
format.js { render js: "window.location='/users'" }
else
format.html { render action: "index" }
format.js { render json: @my_object.errors, status: :unprocessable_entity }
end
end
end
感谢任何帮助, - 戴夫
答案 0 :(得分:0)
虽然您的my_object_params
私有方法没有代码,但您可能会错过overall_rank
吗?
答案 1 :(得分:0)
您没有指定视图所针对的操作,但根据您的控制器代码,我假设您正在尝试创建新对象。换句话说,html代码用于新操作。
生成表单时,您在对象内部调用my_object_times
,但它仍然不存在。
<%= f.fields_for :my_object_times do |rt| %>
<div class="field">
<%= rt.label :overall_rank %><br>
<%= rt.text_field :overall_rank %>
</div>
<% end %>