【发布时间】:2015-07-19 18:01:57
【问题描述】:
我是 Rails 新手,正在尝试编写一个简单的抽认卡程序,其中用户有一个 他们正在循环使用的一副词汇卡......
该模型是用户和卡片之间非常直接的关系,其中:
User has_many :cards
Card belongs_to :user
基本要点是用户在索引页面上查看卡片并 单击一个按钮,“翻转”到显示页面,另一边在哪里 显示出来。
已经创建并植入了我的 AR 数据库,目前正在渲染一个 访问和“翻转”我的牌组中的第一张卡片的功能版本, 但我坚持访问第二、第三、第四张卡片等。
我在卡片控制器中尝试了许多不同的 AR 查询变体,以获取卡片组中的下一张卡片,但都没有奏效……这就是我现在卡片控制器中的内容:
def index
@card = Card.all.next
@cards = Card.all
end
`
这是我的卡片模型:
class Card < ActiveRecord::Base
belongs_to :user
def self.next
n = 1
if self.id != Card.all.first.id
Card.all.find_by(id: Card.all.first.id + n)
end
n += 1
end
validates :word_text, presence: true
validates :meaning_text, presence: true
end
这是我的 rake 路线:
Prefix Verb URI Pattern Controller#Action
root GET / cards#index
cards GET /cards(.:format) cards#index
POST /cards(.:format) cards#create
new_card GET /cards/new(.:format) cards#new
edit_card GET /cards/:id/edit(.:format) cards#edit
card GET /cards/:id(.:format) cards#show
PATCH /cards/:id(.:format) cards#update
PUT /cards/:id(.:format) cards#update
DELETE /cards/:id(.:format) cards#destroy
GET /cards/:id(.:format) cards#show
`
.....因此,由于上述原因,下面的代码当然不是我想要的,但这是我现在的视图页面:
<div id="front_page_container" class="medium-8 medium-centered text-center columns">
<div class="row">
</div>
</div>
<div id="box-container">
<br> <br> <%= button_tag(type: 'button') do %>
<h1 style="color:yellow"> <%= @card.word_text %>
<ul><%= link_to 'Tap to flip card', card_path(@card) %></ul>
<ul> <%= content_tag(:strong,'Tap to flip the card') %> </ul>
<% end %></h1>
</div>
<br> <br> <%= button_tag(type: 'button') do %>
<ul><%= link_to 'New Card', cards_path(@next) %></ul>
<ul> <%= content_tag(:strong,'New Card') %> </ul>
<% end %>
说实话,我非常纠结于如何创建从我的索引页面(显示卡 #1 或 @card)返回到新索引页面的路径 其中显示卡 #2 或 @next...任何帮助将不胜感激!
【问题讨论】:
-
如果可以请详细说明翻转逻辑。目前你的下一个方法是错误的。有语法问题。 self 是 next 方法中的类。 self.id 在那里不起作用。
-
该应用程序的基本逻辑是,我的索引页面将显示一张抽认卡的前面......通过点击按钮`link_to'点击翻转卡片',card_path(@card) ` 用户将被带到显示此卡背面的显示页面。这部分工作正常....但我只能看到一张卡。第一个版本在 heroku 上,你可以在这里看到:sheltered-escarpment-2579.herokuapp.com/cards.1thx
标签: ruby-on-rails activerecord model-associations