Rails多对多创建失败

时间:2014-03-16 08:32:41

标签: ruby-on-rails

我有事件和乐队模型,它们通过event_bands具有多对多关系。我正在尝试更改我的创建方法以使用episode 258 of railscasts中的chosen jQuery。我在尝试创建活动时不知道如何从本地主机读取消息:

Started POST "/events" for 127.0.0.1 at 2014-03-16 17:11:07 +0900
Processing by EventsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jx1Cm09uCwJcnY8573ZTRKMjH1BHWhlREFCfhij/AB0=",  "event"=>{"name"=>"pojpj", "ko_name"=>"", "band_ids"=>["", "110"], "venue_id"=>"", "date(1i)"=>"2014", "date(2i)"=>"3", "date(3i)"=>"16", "time"=>"", "contact"=>"", "facebook"=>"", "ticket"=>"true", "price"=>"", "door_price"=>"", "ticket_url"=>"", "info"=>"", "info_ko"=>""}, "commit"=>"등록", "locale"=>"ko"}
Band Load (0.2ms)  SELECT "bands".* FROM "bands" WHERE "bands"."id" = ? LIMIT 1  [["id", 110]]
(0.1ms)  begin transaction
Band Exists (1.0ms)  SELECT 1 AS one FROM "bands" WHERE ("bands"."name" = '...Whatever That   Means' AND "bands"."id" != 110) LIMIT 1
(0.2ms)  rollback transaction
Redirected to http://localhost:3000/events/new

看起来它失败了,因为Band已经存在于数据库中,但是为什么它会这样做而不是创建关系?

def new
    @event = Event.new
end

def create
    @event = Event.new(event_params)
    if @event.save
        flash[:notice] = "Event Created!"
        redirect_to event_path(@event)
    else
        flash[:notice] = "Event not created!"
        redirect_to new_event_path
    end
end
    private

  def event_params
    params.require(:event).permit(:name,
        :ko_name,
        :avatar,
        :time,
        :facebook,
        :ticket,
        :door_price,
        :ticket_url,
        :info_kr, 
        :contact, 
        :price,
        :info,
        :info_ko, 
        :venue_id, 
        :date,
        band_ids: [])
  end

表格的相关部分:

<p>
    <%= f.label "Bands" %><br />
    <%= f.collection_select :band_ids, Band.order(:name), :id, :name, {}, {multiple: true} %>
</p>

我在模型中有accepts_nested_attributes_for :bands,我认为关系设置正确,因为我可以a = Event.new(name: 'asdf', band_ids: [1,5]) a.save并且它是持久的。

更新:问题似乎来自band_ids中的空白项目。出于某种原因,rails将参数设置为band_ids: ['',3,5]。我可以通过尝试在控制台中创建一个新条目来复制来自我的服务器的SQL消息:a = Event.create(name: 'asdfasdfasdfasdf2345', band_ids: ['', 3, 2])。但空的第一个项目来自哪里?

edit2:忽略上述情况,似乎问题实际上是在关联中没有event_id使用?

@messages={:"event_bands.event_id"=>["에 내용을 입력해 주세요"]}

0 个答案:

没有答案