私は、それぞれbelongs_toとhas_manyの関係を持つPostとSubCategoryモデルを持っています。
Post の Show ビューでは、個々の Post を表示するだけでなく、SubCategory コントローラのインデックス アクションを実行して、現在の SubCategory とそのすべての Post を左側のナビゲーション エリアに表示する必要があります。
これについて最善の方法は何ですか?
EDIT私はすでにApplication Controllerを利用していたので、特に他のビューで同じことをしたい場合は、これが最善の方法だと思います。
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :load_application_wide_varibales
def load_application_wide_varibales
def get_subcategory_and_post
@sub_category = SubCategory.all
end
end
class PostController < ActionController::Base
before_filter :get_subcategory_and_post, only: [:show]
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
class SubCategoryController < ActionController::Base
before_filter :get_subcategory_and_post
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
end
投稿 表示 ビュー
<% @sub_category.each do |subcat| %>
<div class="leftnav">
<h1 class="name"><%= subcat.name %></h1>
<% subcat.posts.each do |post| %>
<ul>
<li><%= link_to (post.name), post %></li>
</ul><% end %>
</div>
<% end %>
<div class="rightContent">
<p id="notice">
<%= notice %>
</p>
<p>
<b>Name:</b>
<%= post.name %>
</p>
<p>
<b>Content:</b>
<%= post.content %>
</p>
</div>
投稿モデル:
class Post < ActiveRecord::Base
belongs_to :sub_category
belongs_to :users
validates :name, :content, :sub_category_id, :presence => true
attr_accessible :content, :name, :sub_category_id
after_save :expire_post_all_cache
after_destroy :expire_post_all_cache
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |post|
csv << post.attributes.values_at(*column_names)
end
end
end
def self.all_cached
Rails.cache.fetch('Post.all') { all }
end
def expire_post_all_cache
Rails.cache.delete('Post.all')
end
end
サブカテゴリ モデル:
class SubCategory < ActiveRecord::Base
attr_accessible :name
belongs_to :category
has_many :posts
validates :name, :category_id, :presence => true
end
ビューを表示:
<div class="leftnav">
<h1 class="name"><%= @post.sub_category.name %></h1>
<% @post.sub_category.posts.each do |post|%>
<ul>
<li><%= link_to (post.name), post %></li>
</ul><% end %>
</div>
<div class="rightContent">
<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= @post.name %>
</p>
<p>
<b>Content:</b>
<%= @post.content %>
</p>
</div>