开发者

How to have predefined categories?

开发者 https://www.devze.com 2023-03-13 03:32 出处:网络
I want my users to be able to select from predefined values of categories. I took a look at other Stackoverflow questions but didn\'t get them fully. Here is my code right now....

I want my users to be able to select from predefined values of categories. I took a look at other Stackoverflow questions but didn't get them fully. Here is my code right now....

I have my Categories model and Users create prices (which is another name for Items).

class Category < ActiveRecord::Base
    has_many :prices

    def name
        "#{category}"
    end
end

My prices belong to categories. note: The prices table has a category_id.

class Price < ActiveRecord::Base
    attr_accessible :name, :date, :price

    belongs_to :user
    belongs_to :category
end

Here is how the form and view look as of now:

Form

<%= form_for(@price) do |f| %>
  <div class="field开发者_运维知识库">
    <%= f.label :date %><br />
    <%= f.date_select :date %>
  </div>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br />
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <%= f.label :category %><br />
    <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => true  %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

View

<p><b>User:</b><%= @price.user_id %></p>  
<p><b>Date:</b><%= @price.date %> </p>
<p><b>Name:</b><%= @price.price_name %></p>
<p><b>Price:</b><%= number_to_currency(@price.price) %></p>
<p><b>Category:</b><%= @price.category.name %></p>

How do i create the categories i want in the drop down menu?

Thank you I'm a very appreciative!


You probably want the collection_select form helper method: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

It will look something like this:

<div class="category">
  <%= f.label :category %><br />
  <%= f.collection_select :category, Category.all, :id, :name %>
</div>

Then in the view:

<p><b>Category:</b><%= @price.category.name %></p>

This assumes that your categories table has a name field which stores the category names.


you can create your data in db/seeds.rb

rake db:seed to load them (Load the seed data from db/seeds.rb)

http://railscasts.com/episodes/179-seed-data for more details

0

精彩评论

暂无评论...
验证码 换一张
取 消