0

Here is my controller action

@posts = Post.where(sub_category_id: params[:id]).paginate(page: params[:page], per_page: 2).to_a

The post table contains category_id,sub_category_id,product_id. All there are three tables

Now i need the mapping name from the id. how can i achieve it.

I tried @sub_category = SubCategory.find params[:id] to get sub category it works fine.

Whether above method is good? If yes how can i achieve it to get other table datas.

Edit-1

I am having table post with following fields

  1. id
  2. category_id
  3. sub_category_id
  4. product_id
  5. title

I am having following set of tables

  1. category
  2. sub category
  3. product

In my view my title is hyperlink. When i click on it. It will redirect to respected post page and i have to show a breadcrum like this Electronics->Laptop->Dell

Edit-2

I tried it but getting error as

undefined method `category_id' for #<ActiveRecord::Relation::ActiveRecord_Relation_Post:0xb4e7a9f0>

Tried the following

  @posts = Post.where(sub_category_id: params[:id]).paginate(page: params[:page], per_page: 2).to_a
  @category = Category.find(@posts.category_id) unless @posts.blank?
4

2 に答える 2

0

次のように、リンクにパラメーターを追加する必要があります

<a href='/controller/post?category_id=1&sub_category_id=2&product_id=3'>click-here</a>
于 2013-09-29T18:41:21.523 に答える
0

あなたまたは他のアクションに があるpost場合show、次のように値を取得できます。

# PostsController#show
...
@post = Post.find(params[:id])
@category = Category.find(@post.category_id)
@sub_category = SubCategory.find(@post.sub_category_id)
@product = Product.find(@post.product_id)

次に、あなたの見解で:

# show.html.erb
...
<%= @category.name + ">>" + @sub_category.name + ">>" + @product.name %>

.nameこれは、必要なテキストを取得するためのメソッドがそれぞれにあることを前提としています。Category//が見つからない場合も処理する必要があります。そのSubCategory場合は. でメソッドを呼び出すことはできないため、その場合を処理するために何かをする必要があります。からのテキストのみが必要で、他の情報が必要ない場合の、これを行う方法の一例:Productnil.namenilCategory

@category = Category.find(@post.category_id)
@category_name = @category.name unless @category.blank?
于 2013-09-29T20:07:42.587 に答える