0

我正在尝试在单击时添加一个唯一条目,以便用户可以接受他们被邀请参加的活动。用户应该只能单击此链接一次。目前我有以下代码似乎正在添加条目,虽然我认为它不是最佳实践,而且唯一 id 似乎不太好用

哈姆

             %li= link_to 'Add', availabilities_path(:availability => {:team_id => @event.team_id, :user_id => user, :event_id => @event.id, :unique_id => availability_unique_id(user,@event) }), :remote => true, :method => :post, :class => 'button tiny success'

模型

validates :unique_id, :presence => true, :uniqueness => true

独特的方法

def availability_unique_id(player,schedule)
    Base64.encode64("#{player.to_s}_#{schedule.id.to_s}_#{schedule.team.id.to_s}")
  end

正如您从下面的查询中看到的那样,没有忽略唯一值

select * from availabilities where user_id = 41;
 id | available | user_id | team_id | event_id |         created_at         |         updated_at         |            unique_id             | comment 
----+-----------+---------+---------+----------+----------------------------+----------------------------+----------------------------------+---------
 61 |           |      41 |         |          | 2012-11-04 13:48:22.794214 | 2012-11-04 13:48:22.794214 | NDFfNDNfMQ==                    +| 
    |           |         |         |          |                            |                            |                                  | 
 84 |           |      41 |       1 |       75 | 2013-02-09 14:03:29.792374 | 2013-02-09 14:03:29.792374 | IzxVc2VyOjB4YWY3NTMxND5fNzVfMQ==+| 
    |           |         |         |          |                            |                            |                                  | 
 85 |           |      41 |       1 |       75 | 2013-02-09 14:06:04.131862 | 2013-02-09 14:06:04.131862 | IzxVc2VyOjB4YjJhODBiOD5fNzVfMQ==+| 
    |           |         |         |          |                            |                            |                                  | 
 87 |           |      41 |       1 |       75 | 2013-02-09 14:07:31.77788  | 2013-02-09 14:07:31.77788  | IzxVc2VyOjB4YjBhYjdiMD5fNzVfMQ==+| 
    |           |         |         |          |                            |                            |                                  | 
4

1 回答 1

0

从评论中。下面的验证确保您user_id对每个event_id. 如果需要,您可以添加多个范围。

validates :user_id, uniqueness: { scope: :event_id }
于 2013-02-10T02:39:22.203 回答