Los rieles muestran técnicas por categoría de la tabla asociada

Categories table looks like this (omitting extraneous info):

  `category` varchar(255) 
  `spanish` varchar(255) 

Techniques table:

  `order` int(11) 
  `korean` varchar(255) 
  `spanish` varchar(255)
  `category_id` int(11)
  `belt_id` int(11)

Associations have been set up:

class Technique < ActiveRecord::Base
    belongs_to :belt
    belongs_to :category
class Category < ActiveRecord::Base
   has_many :technique, :order => 'techniques.belt_id, `order`'

I'd like to show the Techniques in their own page but grouped by categories, not each one individually as I have now. Would also like to be able to edit them and add techniques to a specific category.

preguntado el 08 de noviembre de 11 a las 16:11

1 Respuestas

This can be done quite easy. You do this by passing the value of a category as a hidden option in the create/edit form of a technique, basically you are combining the two forms. On the index of the techniques you can do the same, combine it with the index of categories to list all techniques under a certain category.

en tu controlador

class TechniqueController < ApplicationController
  def index
    @categories = Category.all

en la vista

<% @categories .each do |category| %>
  <!-- some category html -->
  <% category.techniques .each do |technique| %>
    <!-- technique html -->
  <% end %>
<% end %>

respondido 08 nov., 11:21

This is almost what I want, but this produces first a list of categories, then the techniques. I was looking to display the category name and then the list under each one. - kakubei

Ok, never mind, I got it, it was bad HTML, this does the trick nicely. Thanks! - kakubei

As a followup to this, this bit prints out the proper output: #{technique.korean} but sometimes it's empty and when I try to do this: if technique.korean.empty? I get an error unknown method empty, but it should work no? - kakubei

Also, given this <% @belts.each do |belt| %> <h3><%= "#{belt.belt}" %></h3> <% belt.technique .each do |technique| techText = "(#{technique.order}) #{technique.korean} - #{technique.spanish}" %> <%= techText %> <br /> which works fine, but I want to again group the techniques by category inside each belt yet I can't quite figure out how to do it because there is no correlation between belts and categories, just belts and techniques. - kakubei

you should do a check on technique.korean.nil? if it doesnt exist. .empty? only works for a few objects, and they have to be NOT null, it checks for arrays if they have entries for example. - Benjamin Udink ten Cate

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.