【发布时间】:2015-07-30 18:10:26
【问题描述】:
在我当前的本地博客网站上,我可以创建类别和子类别。
我希望在创建帖子时,一旦您从下拉列表中选择类别,它将只显示可用的子类别。
示例:
在本例中,“选择了新闻”。所以我需要做两件事。首先,将我制作的子类别分配给特定类别。其次,根据选择的类别相应地显示子类别。
后模型
class Post < ActiveRecord::Base
belongs_to :category
belongs_to :subcategory
has_many :comments
end
新帖子视图
<h2>Add New Post</h2>
<div class="well">
<%= form_for [:admin, @post] do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title ,class:'form-control' %>
</div>
<div class="form-group">
<%= f.label :category %>
<%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
</div>
<div class="form-group">
<%= f.label :image %>
<%= f.file_field :image %>
</div>
<br>
<div class="form-group">
<%= f.label :subcategory %>
<%= f.select :subcategory_id, Subcategory.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
</div>
<div class="form-group">
<%= f.label :body %>
<%= f.text_area :body ,class:'form-control', id:'eg-textarea' %>
</div>
<br>
<%= f.submit "Submit", class:'btn btn-primary' %>
<%=link_to "Cancel", admin_posts_path, class:'btn btn-default' %>
<% end %>
</div>
帖子控制器
class Admin::PostsController < Admin::ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to admin_posts_path
end
def edit
end
def update
end
def index
@posts = Post.all
end
def show
end
def destroy
end
private
def post_params
params.require(:post).permit(:title, :category_id, :subcategory_id, :image, :body)
end
end
【问题讨论】:
标签: ruby-on-rails ruby sqlite ruby-on-rails-4 model-view-controller