gpt4 book ai didi

ruby-on-rails - 嵌套表单 has_many

转载 作者:行者123 更新时间:2023-12-04 06:18:12 24 4
gpt4 key购买 nike

我不确定如何正确创建带有嵌套表单的 rails 表单。我已经学习了很多教程,但越来越困惑它应该是什么,单数复数, Controller ......这里是我的模型

模型/事件.rb

  attr_accessible :description :title, :tag_ids, :locations_attributes
has_many :location
accepts_nested_attributes_for :location, :allow_destroy => true

模型/位置.rb
  attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
belongs_to :customer
belongs_to :event

Controller 文件
  def new
@event = Event.new
...
def create
@event = Event.new(params[:event])
...

查看form.html.erb
<%= form_for(@event) do |f| %>
<%= f.fields_for :locations do |e| %>
<%= e.text_field :longitude %>
<%= e.text_field :latitude %>
<% end %>
...
<% end %>

错误
Can't mass-assign protected attributes: locations

参数发送
 "locations"=>{"longitude"=>"45.6666",
"latitude"=>"47.44444665"},

我的关系是错误的,因为 fields_for 不支持它,或者我的 Controller 不合适,或者 rails 不是一种很好的语言,或者我不再理解它了。

最佳答案

你快到了...

event.rb - 位置不是位置

attr_accessible :description :title, :tag_ids, :locations_attributes
has_many :locations
accepts_nested_attributes_for :locations, :allow_destroy => true

我认为应该这样做

编辑

正如 Valery Kvon 所说,你需要添加
@event.locations.build

到您的 Controller

关于ruby-on-rails - 嵌套表单 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com