Ruby on Rails Sunday, November 22, 2015

Colin Law <clanlaw@gmail.com> writes:

> On 21 November 2015 at 18:50, fugee ohu <fugee279@gmail.com> wrote:
>
>> i'm trying to follow these instructions:
>>
>> in my categories_controller.rb
>> def index @parent_categories = Category.without_parents
>>
>> in my index.html.erb
>> <ul> <%= render @parent_categories %> </ul>
>> in my _categories.html.erb
>> <ul> <li> <strong><%= category.name %></strong> <ul> <%= render
>> category.categories %> </ul> </li> </ul>
>> but this doesn't work i get unknown method wihtout_parents and couldn't
>> figure out what without_parents was supposed to be so, i tried changing the
>> line in the controller to @parent_categories =
>> Category.where("parent_id=0") and it was on to the next error, now i get
>> undefined method `categories' for #<Category:0xb1604e2c> My understanding
>> is that in the statement, category is the partial view and categories means
>> the entire collection, so then why doesn't rails recognize the meaning of
>> categories as the entire collection and what's the story with
>> "without_parents" ? ~ thanks, fugee
>>
>
>
> I am afraid your ideas are so horribly mixed up it is difficult to know
> where to start. I think the instructions you are following must be rather
> poor. I suggest instead you start by working right through
> railstutorial.org (which is free to use online) which will show you the
> basics of Rails in a way which most can follow.
>
> Colin

As ever, Colin's advice is correct. Do work through a full tutorial,
maybe two or three times, even.

Notwithstanding that, there are a couple things you're trying to do
here.

1. defined scopes

the `.without_parents` would be a *scope* you have to define as a Class
Method on your Category model. It's essentially like so:

class Category < ActiveRecord::Base
# ...

scope :without_parents, ->() { where( parent_id: 0 ) }

# ...
end

See http://guides.rubyonrails.org/active_record_querying.html#scopes


2. partials for collections


See http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
subsection 3.4.5 Rendering Collections. When you have a collection of
categories, as you do with `@parent_categories`, you name the partial
`category.html.erb` (NOTE SINGULAR) and the variable available inside
that partial is also `category` (again singular) and it contains ONE
category from `@parent_categories` at a time.


--
Tamara Temple
tamouse@gmail.com
http://www.tamouse.org

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/m2wptarsye.fsf%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment