Reputation: 730
I am challenging myself to build a little marketplace where you will be able to post a "request" inside a category. For that I have both the request model and the category model. How can I add a relation between those models, so that the Category knows that it belongs to a request and vice versa? I already did:
category.rb
has_and_belongs_to_many :requests
request.rb
has_one :category
Now inside my form partial I have this code:
<%= f.select :category, Category.all, :prompt => "Kategorie", class: "form-control" %>
The strange thing is :category
does not exist, as the column should be :name
. In my seeds.rb
I've inserted the following, which runs fine after rake db:seed
Category.create(name: 'PHP')
Category.create(name: 'Ruby')
Category.create(name: 'HTML')
Category.create(name: 'ASP')
Category.create(name: 'C#')
Category.create(name: 'C++')
But the above code with :category
shows this:
There are all 6 Categories from the seed file, but not the actual name of the category (like "PHP"). If i'm taking :name
instead of :category
in this code:
<%= f.select :category, Category.all, :prompt => "Kategorie", class: "form-control" %>
I am getting a
undefined method `name' for #<Request:0x007ff504266b40>
My Category table:
Category(id: integer, name: string, description: text, created_at: datetime, updated_at: datetime)
How can I call the category for a specific request, when it's saved? @Category.request
?
I'm really confused (sorry I'm learning Rails only since late August).
MANY Thanks in Advance!
Upvotes: 1
Views: 877
Reputation: 5802
If I understand it correctly, as in one Request belongs to one category and one category can have multiple requests the associations should be set up like this:
class Request < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :requests
end
Like this the entries in request table will have the foreign key category_id to the category.
You can also read a lot about association basics in the Active Record Associations Guide
How can I call the category for a specific request, when it's saved? @Category.request ?
To get the category for a specifc request you have to start from the request for example like this:
@request = Request.first
@reqest.category
In your form you probably then have to use category_id
if you want to use the select tag like this:
<%= f.select :category_id, Category.all.map { |c| [c.name, c.id] }, :prompt => "Kategorie", class: "form-control" %>
The map will make sure that it will use the name for the label and the id for the value in your select.
To make generating forms for associations and other stuff easier you can also have a look at the gem simple_form. Then all you have to use is:
<%= f.association :category %>
Upvotes: 1