Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
Hi everyone, i've working with rails and i can't understanding something...let me make it clear:
I have two tables, obviously two models:
employes:
id category_id
category:
id description
One category can be used for many employes, and one employ belongs to ONE category.
how can i make that?
employ: has_one :category
category: belongs_to :employ
OR
employ: belongs_to :category
category: has_many :employes
I need to do something that meke possible use "@employ.category" and thats return the category of the employ, and "@category.employes" and thats return all employes with that category.
Hope someone can help me =\
Thank's
employ: belongs_to :category
category: has_many :employes
One very simple rule which will let you deduce the other relationships. The belongs_to declaration is always on the model which has the foreign key in its table. So here, @employees@ has the @category_id@ foreign key, so the Employee model will have the @belongs_to :category@ declaration.
I'm very unsure about your use of words like employ and employes. The usual here would be to have the @Employee@ model, with the @employees@ table and then, in @Category@ you would have a @has_many :employees@ declaration. If you really want an @Employ@ model and the plural of that is @employes@ then you'll need a custom inflection.
Jason King,
Good Reply. we should fallow naming convention strictly in ruby on rails.
I have a similar problem. Am a newbe as well.
My categories are already created i.e
categories: id name
posts: id category_id title excerpt body ....
Category has_many :posts
Post belongs_to :category
How do I ensure that during the creation of a post, using a checkbox or radio button, the selected category is updated in the data base?
So that if I do @jobs.category.find(params[:category_id]) if this is right, I get a list of jobs under that category?
What should I do in the controller/model methods?
Sorry for my noobishness
Thanks
Nelson,
Firstly if you are looking for all the jobs under a category I would suggest:
Category.name_equals('cool_category').posts
That will find the category of a given name and then all of the posts for that category.
When you are creating the post all you need to do is set the category_id to the category you want. I would suggest looking into "formtastic":http://github.com/justinfrench/formtastic to create elegant forms.
hope this helps
