如何在Post中添加下拉列表?

时间:2016-05-03 17:44:48

标签: ruby-on-rails ruby

如何在Post的新页面中添加所有可能类别的下拉列表?

这是当前的设置(由于在线各种教程的拼凑,这是非常零碎的)。如果有更多信息我应该添加,请告诉我。谢谢。

发布模型

class Post < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, :through => :categorizations

    has_many :comments, as: :commentable
end

类别模型

class Category < ActiveRecord::Base
    has_many :categorizations
    has_many :posts, :through => :cateogorizations
end

分类模型

class Categorization < ActiveRecord::Base
    belongs_to :post
    belongs_to :category
end

发布_form.html.erb

    <%= form_for(@post) do |f| %>
      <% if @post.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

          <ul>
          <% @post.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>

      <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :title %>
      </div>
      <div class="field">
        <%= f.label :body %><br>
        <%= f.text_area :body %>
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

分类_form.html.erb

<%= form_for(@categorization) do |f| %>
  <% if @categorization.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@categorization.errors.count, "error") %> prohibited this categorization from being saved:</h2>

      <ul>
      <% @categorization.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.select :post_id, Post.all.collect {|p| [p.title, p.id]} %>
  </div>
  <div class="field">
    <%= f.select :category_id, Category.all.collect { |p| [p.name, p.id ]} %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

修改

我能够用这一行以Post的形式出现:

<%= collection_select(:post, :category_ids, Category.all, :id, :name, {}, { :multiple => true } )%>

实际上,迷你秒更新,我把它改成了这一行:

<%= select("post", "category_ids", Category.all.collect { |p| [p.name, p.id] }) %>

因为我想要一个下拉列表本身,而不是一个集合列表。

耶!如何让它显示在Post的显示页面中?

0 个答案:

没有答案