多くのロジックをビューからコントローラ/モデルに移動する方法を理解しようとしています。ビューからコントローラへの関数の移動Rails 5
(私はモデルに行くことになっていると思う?)
Show.html.erb
<div class="collectionList">
<% @user.collections.each do |d| %>
<%= d.name %>
Distinct Cards: <%= d.card_collections.count %> <br />
Total Cards:
<% d.card_collections.each do |x| %>
<% y = [] %>
<% y << x.card_counts %>
<% y.flatten! %>
<% y = y.inject(0){|sum,x| sum + x } %>
<%= y %>
<% end %>
<% if d.public %> Public <% end %><br />
<% end %>
</div>
すべてのユーザは、各コレクションはcard_collectionを持つことができ、コレクション、それぞれを持っていますそれらのうちの1つはカードを持つことができます。
「card_collections」の量は、あなたのデッキに別々のカードの量です。 「card_collections.card_counts」の合計は、カードの合計額です。私はそれを私はそれのように呼び出すことができますが、私はどのようにわからないモデルで 'カードの合計'と 'カードの数'としてそれを定義すると思っています。
また、私はより高速な結果を得るために摘む/合計を使用することができますので、私がモデルにそれを動かすことができれば、私のロジックが容易になるだろうと思いますか?
コレクション
class Collection < ApplicationRecord
belongs_to :user
has_many :card_collections
has_many :cards, through: :card_collections
# validates :user_id, presence: true
end
カード
class Card < ApplicationRecord
has_many :card_collections
has_many :collections, through: :card_collections
belongs_to :deck, optional: true
end
ここCardCollection
class CardCollection < ApplicationRecord
belongs_to :collection
belongs_to :card
end
あなたは、テーブル間の関係(ではあり-多くが属する-に構造)、コントローラとモデルのフィールドでshowメソッドを説明してくださいすることができます。 –