aidiah aidiah - 6 months ago 9
Ruby Question

freindly_id returns 0 for named url

Using the line:

@post = Post.friendly.where!(:board_id=>params[:board_id]).find(params[:id])


to separate posts
:board_id
returns a
0
when the url is
/board1/thread/1/
, but returns the correct value of
1
when the url is
/1/thread/1/


How can I get the correct value of either
1
, or possibly the board slug of
board1
?

Edit:

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

Answer

According to the documentation something like this should work for you:

@post = Board.friendly.find(params[:board_id]).posts.friendly.find(params[:id])

Be aware that this will execute two queries - one for finding the board, and another for finding the post within that board.

There are ways to do this in a single query (for example with a left outer join), although they would introduce coupling with the friendly id configuration you use on the Board model. Example:

Post.includes(:board).where('boards.slug' => params[:board_id]).friendly.find(params[:id])