Rails-在表单中找不到ID [英] Rails - Id can't be found in Forms

查看:72
本文介绍了Rails-在表单中找不到ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一段时间我陷入了这个问题.我正在尝试通过一个表格传递3个ID,以将数据保存在我的数据库中.

Have some time I'm stuck in this problem. I'm trying to pass 3 Id's through a form to save the data in my database.

def new
  @person = Person.find(params[:person])
  @honored = Person.find(params[:honored])
  @group = Group.find(params[:group_id])
  @honor = Honor.new
end

def create
  @person = Person.find(current_person)
  @honor = Honor.create(:group => Group.find(params[:group_id]),
           :person => Person.find(params[:person]),
           :honored => Person.find(params[:honored]))
 if @honor.valid?
  flash[:success] = "Honor created."
  redirect_to (:back)
 else
  redirect_to (:back)
 end
end

在我看来,我调用new方法:

In my view where I call the new method:

<% @asked_groupmembership.each do |agm| %>
<%= link_to "Create Honor", new_honor_path(:group_id => @group.id, :person => current_person.id,
  :honored => agm.member.id) %> 

我的表格:

<% form_for @honor do |f| %>

 <%= f.hidden_field :group_id, :value => @group.id %>
 <%= f.hidden_field :person, :value => current_person.id %>
 <%= f.hidden_field :honored, :value => @honored.id %>

 <div class="field">
<%= f.label :texto %><br />
<%= f.text_field :texto %>
 </div>

当我单击提交"按钮时,出现此错误:

When I click the submit button I get this error:

Couldn't find Group without an ID

app/controllers/honors_controller.rb:22:in `create'

{"utf8"=>"✓",
 "authenticity_token"=>"C7wofMY4VcyfdS10oc3iglex8nZVBMQ0Nh22nMiaOqs=",
 "honor"=>{"group_id"=>"39",
 "person"=>"2",
 "honored"=>"44",
 ...
                },
 "commit"=>"Insert"}

我该如何解决? 谢谢.

How can I solve this? Thanks.

## EDITED ##

class Honor < ActiveRecord::Base
  belongs_to :person, :class_name => 'Person', :foreign_key => "person_id"
  belongs_to :honored, :class_name => 'Person', :foreign_key => "honored_id"
  belongs_to :group, :class_name => 'Group', :foreign_key => "group_id"

推荐答案

您需要使用以下方法更新您的create方法:

You need to update your create method with:

def create
  @person = Person.find(current_person)
  @honor = Honor.create(:group_id => params[:honor][:group],
           :person_id => params[:honor][:person],
           :honored_id => params[:honor][:honored])
 if @honor.save
 ...
end

因为提交表单后,您的数据就以params [:honor]的形式存在.您可以在问题中发布的代码中看到传递给控制器​​的哈希值:

Because after submitting your form you got your data in params[:honor]. You can see the hash passed to the controller in the code posted in your question:

"honor"=>{"group"=>"39",
 "person"=>"2",
 "honored"=>"44",

这篇关于Rails-在表单中找不到ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆