Has_many通过集合连接自动添加到错误的数组

时间:2013-09-14 15:05:30

标签: ruby-on-rails arrays activerecord associations has-many-through

上午, 我有3个型号 - 用户,事件&签

用户可以是与会者或共同发言人。关系/集合连接有效。 无论何时我创建一个事件;它会自动将它们添加到共同扬声器阵列。在我的create方法中,它应该只将它们添加到与会者数组。

调用 @ event.attendees 会给我current_user这是正确的,但是对于 @ event.cospeaker 它会返回相同的内容。

user.rb

has_many :checkins
has_many :events, :through => :checkins

checkin.rb

belongs_to :user
belongs_to :event

event.rb

has_many :checkins
has_many :attendees, :through => :checkins, :source => :user
has_many :cospeakers, :through => :checkins, :source => :user
belongs_to :owner, :class_name => "User"

事件控制器

def create
@event = current_user.events.build(params[:event])
 if @event.save
     @event.owner = current_user

     @event.attendees << current_user
     @event.save
    redirect_to checkin_event_path(:id => @event.id)
 end
end

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

has_many :attendees, :through => :checkins, :source => :user
has_many :cospeakers, :through => :checkins, :source => :user

has_many through:与has_and_belongs_to_may相同,只是链接表有自定义名称。您实际上是在说“事件参与者是签入表中的任何用户”,“事件合作伙伴是签入表中的任何用户”。你可以看到为什么会返回相同的结果。

您需要做的是在checkins表中添加一个标志,然后通过以下方法向has_many添加一个条件:假设您在checkins表中添加了“is_cospeaker”布尔值,您可以这样做:

has_many :attendees, through: :checkins, source: :user, conditions: {is_cospeaker: false}
has_many :cospeakers, through: :checkins, source: :user, conditions: {is_cospeaker: true}

(注意,这是Ruby 1.9+哈希语法。希望你使用的是Ruby 1.9或2.0)

相关问题