刘华佼的全栈学习记录

如何能实际在xxx里发表文章,使用者可以在xxx里看到文章一览表

| Comments

目标

实际在xxx里发表文章,使用者在xxx里可以看到文章一览表

步骤一:在xxxs#show新增“发表文章”按钮

在app/views/xxxs/show.html.erb里增加:
<%= link_to("Write a Post", new_group_post_path(@group), class: "btn btn-default pull-right")%>

步骤二:实作new/create action

class PostsController < ApplicationController

  before_action :authenticate_user!, :only => [:new, :create]

  def new
    @xxx = xxx.find(params[:xxx_id])
    @post = Post.new
  end

  def create
    @xxx = xxx.find(params[:xxx_id])
    @post = Post.new(post_params)
    @post.xxx = @xxx
    @post.user = current_user

    if @post.save
      redirect_to xxx_path(@xxx)
    else
      render :new
    end
  end


  private

  def post_params
    params.require(:post).permit(:content)
  end

end

步骤三:

新增new页面

<h2 class="text-center">新增文章</h2>

<div class="col-md-4 col-md-offset-4">
  <%= simple_form_for [@xxx,@post] do |f| %>
    <div class="form-xxx">
      <%= f.input :content, input_html: { class: "form-control"} %>
    </div>
    <div class="form-actions">
      <%= f.submit "Submit", disable_with: "Submiting...", class: "btn btn-primary"%>
    </div>
  <% end %>
</div>

步骤四:修改 xxxs/_controller 中的 show action

  def show
    @xxx = xxx.find(params[:id])
    @posts = @xxx.posts
  end

步骤五:修改 xxxs/show.html.erb

  <p><%= @xxx.description %></p>

  <table class="table">
    <thead>
     <tr>
        <th>文章内容</th>
        <th>发表者</th>
        <th>发表时间</th>
      </tr>
    </thead>
    <tbody>
      <% @posts.each do |post| %>
        <tr>
          <td><%= post.content %></td>
          <td><%= post.user.email %></td>
          <td><%= post.created_at %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

步骤六:加上对空文章的验证

app/models/post.rb
validates :content, presence: true

Comments

comments powered by Disqus