Reputation: 973
I have a form to create events and also i have a model for category selection
the event model is given by
class Event < ActiveRecord::Base
belongs_to :category
end
and i have t.belongs_to :category
in the event migration and i have t.string :name
in the category migration
i have done this so as to select a single category for the event
but now i also want to select the multiple interest for the event and their names must be fetched from the category table so as to store the category_id in another column(interest) in the events table.
I am doing it so as to find users who belongs to the same category (i have also included category id in the user table )
please tell me how it can be done ? thanks in advance
UPDATE 1 - actually i want to store the interest in category for the event like the event belongs to arts category and it needs to find users and other events who belongs to arts, commerce, science etc .... this is interest of the event
UPDATE 2 - so that in its show view i can fetch the users and other events who belongs to the category which the events has in its interests
Upvotes: 0
Views: 1906
Reputation: 2519
It's a little bit of a hacky workaround to do this, but it is possible:
Model
In your model add:
class Event < ActiveRecord::Base
serialize :interests
end
View
Given that @categories
contains all the categories, you can make checkboxes of interests like this (put this in your view for the event):
<tbody>
<% @categories.each do |category| %>
<tr>
<td><%= check_box_tag "interests[]", category.id %></td>
</tr>
<% end %>
</tbody>
Controller
When you submit the form, you will receive them in this format:
"interests[]"=>["3", "4", "5"]
You can reach those values by using params[:event][:interests]
or params[:interests]
, depending if the form is wrapped or not. You can check the parameters in your terminal, when you post the form.
In the first case, the results will be automatically sent to the model, but in the second case, where you have only params[:interests]
you need to manually assign them upon creation, like this:
@event.interests = params[:interests]
Eitherway, you are trying to get an array in a column, so you need to serialize it. That's why there's a serialize
in the model. Additionally, you have to have your column value as a text
(t.text) , not as a string.
In theory, each time you reach Event.interests , you will get an array which you can iterate through with each
Upvotes: 2