使用线:
@post = Post.friendly.where!(:board_id=>params[:board_id]).find(params[:id])
分隔帖子:board_id
会在网址为0
时返回/board1/thread/1/
,但在网址为1
/1/thread/1/
值
如何获得1
的正确值,或者可能是board1
的板块?
编辑:
class Board < ActiveRecord::Base
has_many :posts
has_many :replies, through: :posts
include FriendlyId
friendly_id :name, use: :slugged
accepts_nested_attributes_for :posts, :replies
end
class Post < ActiveRecord::Base
belongs_to :board
has_many :replies, dependent: :destroy
accepts_nested_attributes_for :replies
include FriendlyId
friendly_id :pid, :use => :scoped, :scope => :id
after_create :set_pid
def set_pid
post_max = self.board.posts.maximum(:pid)
reply_max = self.board.replies.maximum(:pid)
if post_max.to_i < reply_max.to_i
self.update_attributes(:pid => reply_max.to_i + 1)
else
self.update_attributes(:pid => post_max.to_i + 1)
end
end
end
答案 0 :(得分:0)
根据documentation这样的事情对您有用:
@post = Board.friendly.find(params[:board_id]).posts.friendly.find(params[:id])
请注意,这将执行两个查询 - 一个用于查找电路板,另一个用于查找该电路板中的帖子。
有一些方法可以在单个查询中执行此操作(例如,使用左外连接),但它们会引入与您在Board模型上使用的友好ID配置的耦合。例如:
Post.includes(:board).where('boards.slug' => params[:board_id]).friendly.find(params[:id])