rsvp按钮(用户只能rsvp一次)

时间:2018-05-21 20:27:10

标签: ruby-on-rails ruby

因此,目前用户可以多次rsvp同一事件。这显然对我的网站有问题所以我希望单个用户只能为特定的帖子/事件进行一次rsvp。在他们制作了他们的Rsvp后,我希望rsvp按钮消失。 Heres是我的代码的样子。

show.html.erb

id="notice"><%= notice %></p>


<p>
  <strong>Date:</strong>
  <%= @post.date %>
</p>

<p>
    <strong>Name:</strong>
    <%= @post.name %>
</p>

<p>
  <strong>User_id:</strong>
  <%= @post.user_id %>
</p>
<p><strong>Address:</strong> <%= @post.address %></p>
<p>
  <strong>Description:</strong>
  <%= @post.description %>
</p>

<p>
    <strong>registered:</strong>
    <%=@post.users.length%>
</p>






<% if current_user == @post.user %>
 <%= link_to 'Edit', edit_post_path(@post) %> |
<%end%>
 <%= link_to 'Back', posts_path %>

<div class="rsvp"><%= button_to "Rsvp now", rsvps_post_path(@post), class: "btn btn-primary" %></div>





<div class="map"><%= image_tag "http://maps.googleapis.com/maps/api/staticmap?center=#{@post.latitude},#{@post.longitude}&markers=#{@post.latitude},#{@post.longitude}&zoom=12&size=450x400&sensor=false&key=AIzaSyCKzKMEhSNgwSXf7WV71pHWgzdpMkPn8W4",
class: 'img-fluid img-rounded', alt: "#{@post} on the map"%>
</div>

post.rb

class Post < ApplicationRecord
belongs_to :user
 geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode


  has_many :rsvps
  has_many :users, through: :rsvps

  validates :name, presence: true

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
         has_many :posts

          has_many :rsvps
          has_many :posts, through: :rsvps

          validates :email, presence: true

rsvp.rb

class Rsvp < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

#rsvp migration

class Rsvp < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

所以我在Stackoverflow中环顾四周并搜索了一下但是我不知所措。我真的很感激能够解决这个问题的答案。我只是想让rsvp按钮显示没有为特定帖子/事件进行过搜索的用户。

1 个答案:

答案 0 :(得分:2)

对我来说最重要的是数据库约束。您希望指示数据库在这些情况下抛出错误。

在迁移中

add_index :rsvps, [:user_id, :post_id], unique: true

反映这一点的验证,只是为了让铁路知道这个

validates :user_id, uniqueness: { scope: :post_id }

现在我们确信数据库中只有一对some_user_id,some_post_id。

现在,让我们指示视图在这些情况下不显示按钮

<% unless Rsvp.exists?(post: @post, user: @post.user) %>
  <div class="rsvp">
    <%= button_to "Rsvp now", rsvps_post_path(@post), class: "btn btn-primary" %>
  </div>
<% end %>

我会在动作中移动存在的查询,并在这里只使用一个布尔值,这只是示范性的。

相关问题