0

I'm very new to ruby and rails so this is probably quite a simple question but very confusing to me.

I have users (with model, controller, views and everything all set up already). Now I want to introduce something where users can indicate what their preferences are. An example would be for users to indicate what their 5 favourite foods are, and then for me to be able to search for users by favourite food.

This being my first rails project, I'm a little unsure how to approach this. My thoughts so far:

1) Add a boolean array to my User model, render the array as checkboxes and then store it somehow. (I'm just not sure how to generate the migration for that, or how to search by food item if implemented like that).

2) Create a Food model and use the has_many relationship in my User model to link users to foods. I imagine I'd then be able to search for users based on a food? I feel like a Food model might be overkill because it's not something that has any information relating to it. It is just something to attach to Users.

Any suggestions, code, hints or tips would be hugely appreciated.

4

1 回答 1

1

首先,您应该使用http://railscasts.com/作为资源。您在此处描述的所有内容,此站点都有教程。

您需要小心地向您的用户模型添加多个字段(即 fav_food_one、fav_food_two 等),因为搜索和返回列表会很麻烦。

您更有可能想要拥有 has_many 关联的东西

User: username, name, email, etc

Food: name, category, fun_facts, etc

UserFavoriteFoods: user_id:integer, food_id:integer

在您的模型中,您将创建这样的关联。

User=> 
  has_many :user_favorite_foods, :dependent => :destroy
  has_many :foods, :through => :user_favorite_foods

Food=>
  has_many :user_favorite_foods, :dependent => :destroy
  has_many :users, :through => :user_favorite_foods  

UserFavoriteFoods =>
  belongs_to :user
  belongs_to :food

然后在你的(我假设 User#Show)视图中,你可以做这样的事情

<% @user.foods.each do |food| %>
 <li><%= food.name %></li>
<% end %>

编辑=>

您还可以使用 gem likesimple_form并将其应用于您的用户表单。

在这种列表中使用f.association :foods会自动弹出一个选择框,让您的用户轻松选择不同的食物。

于 2013-02-25T04:28:52.873 回答