因此,我正在尝试让我的应用程序在用户购买课程的地方看到一个“查看模块”按钮,因为当他们购买课程时会创建一个订单,因此我正在检查订单是否存在。
但是,当前购买课程时,视图模块会显示在所有课程中,但我希望它仅显示在购买的课程中。
这是我到目前为止所拥有的:
schema.rb
create_table "courses", force: :cascade do |t|
t.string "title"
t.text "summary"
t.text "description"
t.string "trailer"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.index ["slug"], name: "index_courses_on_slug", unique: true
end
create_table "orders", force: :cascade do |t|
t.integer "user_id"
t.integer "course_id"
t.float "total"
t.index ["course_id"], name: "index_orders_on_course_id"
t.index ["user_id"], name: "index_orders_on_user_id"
end
未购买
已购买
已经购买了电子邮件营销,但是它们都显示“查看模块”按钮。
这是我做按钮的方式
<section class="flex justify-between px-6 py-4">
<% if user_signed_in? %>
<% if current_user.isAdmin? %>
<%= link_to "Edit", edit_course_path(course), class: "inline-block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<% else %>
<% if Order.exists? %>
<%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<% else %>
<%= form_with(url: '/payments/create') do |f| %>
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-image="https://s3.eu-west-2.amazonaws.com/aurameir-courses/aurameir-logo.png"
data-name="<%= course.title %>"
data-description="<%= course.summary %>"
data-amount="<%= course.price*100 %>"
data-label="Buy Now"
>
</script>
<%= hidden_field_tag(:course_id, course.id) %>
<%= f.submit "Buy now", class: "bg-blue hover:bg-blue-dark w-full text-white font-semibold py-3 px-4 border-2 rounded-sm border-blue-dark shadow outline-none" %>
<% end %>
<% end %>
<% end %>
<% else %>
<%= link_to "View", course, class: "block text-lg text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<span class="inline-block bg-green font-bold text-xl text-white border-2 border-green-dark px-4 py-2 leading-none shadow">£<%= course.price %></span>
<% end %>
</section>
</section>
答案 0 :(得分:0)
此行:
if Order.exists?
将检查是否存在任何订单。也就是说,只要在orders表中至少有一条记录,它就会成立。但是,您要检查特定于 的订单,即当前用户是否订购了特定课程。因此,您可以将其替换为:
if Order.exists?(user: current_user, course: course)
但是,这将运行一个单独的查询来检查每个课程的订单是否存在。一旦您完成了几门课程,这将变得效率低下。因此,最好运行一个查询来查找当前用户订购的所有课程ID,然后对照该列表进行检查。