通过复选框分配给事件

时间:2015-03-01 21:00:21

标签: ruby-on-rails ruby-on-rails-4

我需要分配给事件。我有用户编辑的复选框,我选择事件,然后点击保存后我想用event_id和user_id添加插入到数据库。我不知道这是不是一个好主意,但如果有人有更好的想法,请给我一些建议。

我的观点,在这一刻我只知道我指定的事件:

  <% Event.all.each do |event| -%>
  <tr>
    <td><%= label_tag :event_ids, event.name -%></td>
    <td><%= check_box_tag :event_ids, event.id, @user.event.include?(event), :name => 'user[event_ids][]' -%></td>
  </tr>
  <% end -%>

我的架构:

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
  end

  create_table "events", force: true do |t|
    t.string   "name"
    t.datetime "event_date"
    t.string   "organizator"
    t.string   "email"
  end

  create_table "bookings", force: true do |t|
    t.integer  "user_id"
    t.integer  "event_id"
  end

我的模特:

class User < ActiveRecord::Base
  has_many :bookings
  has_many :events, :through => :bookings

class Booking < ActiveRecord::Base
    belongs_to :user
    belongs_to :event

class Event < ActiveRecord::Base
    has_many :bookings
    has_many :users, :through => :bookings

1 个答案:

答案 0 :(得分:0)

你有用户的地方&gt;预订&gt;活动,我有画廊&gt;进入&gt;照片。

在编辑控制器中:

@photo_ids = []
@gallery.entries.each do |entry|
  @photo_ids << entry.photo.id
end

_form.html.haml的相关部分是:

- @photos.in_groups_of(15, false) do |group|
  %tr
    - group.each do |photo|
      %td
        = label_tag("photo_ids_#{photo.id}", image_tag(photo.image.url(:thumb)))
        = raw('<br/>')
        = check_box_tag "photo_ids[]", photo.id, @photo_ids.include?(photo.id), :id => "photo_ids_${photo.id}"

保存在控制器中时:

if @gallery.save
  photo_ids = params[:photo_ids]
  photo_ids ||= []
  @gallery.entries.each |entry|
    entry_photo_id_s = entry.photo_id.to_s
    # if already in gallery and checked, keep it, and remove from list to add
    if photo_ids.include?(entry_photo_id_s)
      photo_ids.delete(entry_photo_id_s)
    else
      entry.destroy
    end
    # if not already in gallery, add an entry
    photo_ids.each do |photo_id|
      entry = Entry.new
      entry.gallery_id = @gallery.id
      entry.photo_id = photo_id
      entry.save
    end
  end
  blah, blah, blah (render, redirect, whatever)
end

通过实体(以及从HAML到ERB)的少量翻译,这应该适用于您的用户&gt;预订&gt;事件