我在Rails 4中遇到了一個複雜問題,我將在下面進行介紹。我正在使用簡單的表單和awesome_nested_fields寶石。嵌套字段和強參數
我有一大堆的一些領域的活動在我的應用程序
這是我的工作accepts_nested_attributes實施前event_controller PARAMS:
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 %>
更新控制器強參數:
現在10當我啓動我的應用程序,在創建新的事件我得到的:
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
要做的檢查:你的音箱表有'event_id'列?你是否運行遷移? – vee
如果這是一個強烈的參數問題,你很可能會看到一個錯誤,說'不允許的參數 - >參數的名稱'。我會看vinodadhika建議的db表。 – simonmorley
@simonmorley將speaker_id添加到演講者表中。我不明白爲什麼沒有在插件的文檔中提到這一點。但是現在我面臨着一個新問題:在使用嵌套揚聲器編輯和保存事件時,它會複製它們。沒有任何刪除的可能性。強大的參數呢? –