我在Rails 4中遇到了一个复杂的问题,我将在下面尝试介绍。我使用简单的形式和awesome_nested_fields宝石。
我的应用
中包含一些事件和一些字段这是我在accept_nested_attributes实现之前的工作event_controller参数:
private
def event_params
params.require(:event).permit(:title, :description, :type_id, :price, :program,
:start_date, :end_date, :image, category_ids: [])
end
现在我想在我的活动中添加一些发言者,并让用户决定每个活动他想要多少个发言者。所以我正在添加嵌套字段gem并根据他们的文档使扬声器成为嵌套字段。
Event.rb
class Event < ActiveRecord::Base
has_many :speakers
accepts_nested_attributes_for :speakers, allow_destroy: true
end
Speaker.rb
class Speaker < ActiveRecord::Base
belongs_to :event
end
添加发言人(在我的添加活动simple_form_for中):
<%= f.nested_fields_for :speakers do |f| %>
<fieldset class="item">
<%= f.label :name %>
<%= f.text_field :name %>
<a href="#" class="remove">remove</a>
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
</fieldset>
<% end %>
更新强参数控制器:
private
def event_params
params.require(:event).permit(:title, :description, :type_id, :price, :program,
:start_date, :end_date, :image, category_ids: [],
speakers_attributes: [ :name ])
end
现在当我启动我的应用程序时,在创建新事件时,我得到了:
can't write unknown attribute `event_id'
如果我删除
speakers_attributes: [ :name ]
从强大的参数我将能够创建我的事件,但是当我试图查看或编辑它时我会得到
SQLite3::SQLException: no such column: speakers.event_id: SELECT "speakers".* FROM "speakers" WHERE "speakers"."event_id" = ?
当然,数据库中没有创建扬声器。
>> s = Speaker.first
=> nil
我将不胜感激任何帮助或建议。谢谢!
=====
更新了重复问题
事件控制器
def update
@event = Event.find(params[:id])
if @event.update(event_params)
flash[:success] = "Event updated"
redirect_to @event
else
render @event
end
end
event.rb
class Event < ActiveRecord::Base
belongs_to :type
has_many :categorizations
has_many :categories, through: :categorizations
has_many :speakers
accepts_nested_attributes_for :speakers, allow_destroy: true
@today = Date.today
def self.future_events
order('start_date ASC').where('start_date >= ?', @today)
end
scope :current_events, lambda { where('start_date < ? and end_date > ?', @today, @today) }
scope :past_events, lambda { order('end_date DESC').where('end_date < ?', @today) }
scope :future_by_type, lambda { |type| order('start_date ASC').where('type_id = ? and start_date >= ?', type, @today) }
scope :current_by_type, lambda { |type| order('start_date ASC').where('type_id = ? and start_date < ? and end_date > ?', type, @today, @today) }
scope :past_by_type, lambda { |type| order('start_date ASC').where('type_id = ? and end_date < ?', type, @today) }
validates :title, presence: true
mount_uploader :image, ImageUploader
before_save :define_end_date
before_save :zero_price
private
def define_end_date
self.end_date ||= self.start_date
end
def zero_price
if self.price.empty?
self.price = 0
end
end
end
答案 0 :(得分:11)
现在我考虑一下,它可能与强参数有关。要使更新生效,您还需要允许id
属性。在您的许可证参数中添加speakers
的id以及将要更新的任何其他嵌套的嵌套资源。
请试一试:
def event_params
params.require(:event).permit(:title, :description, :type_id, :price, :program,
:start_date, :end_date, :image, category_ids: [],
speakers_attributes: [ :id, :name ])
end