【问题标题】:Creating a Draft State in Ruby on Rails在 Ruby on Rails 中创建草稿状态
【发布时间】:2013-07-21 01:38:50
【问题描述】:

(必须的,我是编码新手,致谢)

我已经使用 Rails 创建了一个简单的博客应用程序,并且还在我的表单中使用了 simple_for gem。我正在尝试使用两个提交按钮创建一个草稿状态。最终目标是让“发布”按钮让所有登录或未登录的用户在索引页面上看到帖子,而“另存为草稿”按钮让只有登录的人才能看到帖子。这是我到目前为止所拥有的。

_form.html.erb:

<div class="actions">
<p><%= f.submit "Publish", :name => "publish" %>
<%= f.submit "Save as Draft", :name => "draft" %></p>   </div>

posts_controller.rb:(不太确定在这里放什么)

def create
    @post = current_user.posts.new(params[:post])


    respond_to do |format|
      if @post.save 
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

index.html.erb:(不确定如何指定使用不同值提交的帖子)

   <% @posts.reverse_each do |post| %>
      <h1 style="font-family: latohairline"><%= link_to post.title, post %></h1>
        <p style="margin-top: -20px"><small>Posted by <%= post.user.name %></small></p>
        <p><%= post.description.html_safe %></p>

        <% if user_signed_in? %>
          <div><p><small><%= link_to 'Edit', edit_post_path(post) %> |
          <%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %></small></p></div>
        <% else %>
        <% end %>

post.rb:(不确定模型中是否需要更改任何内容,但以防万一)

class Post < ActiveRecord::Base
    validates_uniqueness_of :title
    def to_param
      [id, title.parameterize].join("-")
    end
  attr_accessible :description, :title, :image

  validates :user_id, presence: true
  validates :description, presence: true


  belongs_to :user
  has_attached_file :image


end

任何帮助都将不胜感激,我已经在谷歌上搜索了几个小时,但在不知道所有正确的搜索词的情况下,我最终找到了 zilch。谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    如果您对同一个表单使用多个提交按钮,则必须检查params[:commit]。这将设置为提交按钮的名称,因此您可以在控制器中检查

    if params[:commit] == 'draft'
      # save as a draft
    else
      # save as published
    end
    

    您是否也对如何将每个帖子归类为草稿感到困惑?我可能会在您的模型上创建布尔字段,然后基于它创建一些范围:

    scope :drafts, -> { where(draft: true) }
    scope :published, -> { where(draft: false) }
    

    所以保存为草稿只是意味着您将draft 设置为true。然后,您可以使用Post.draftsPost.published 检索任一集以在适当的时候显示它们。

    【讨论】:

      【解决方案2】:

      草稿逻辑最终会变得非常复杂,尤其是如果您想在最初发布后跟踪草稿更新。 (假设我发布了一条记录,但随后开始对其进行我不想发布的编辑。)

      如果您想尝试一下,我已经开始将草稿逻辑提取到名为 Draftsman 的 Ruby gem 中。

      我总是乐于回答问题或收到有关如何改进建议的反馈。草稿是我项目的重要组成部分,所以我希望这个 API 好用!

      【讨论】:

        猜你喜欢
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        • 2013-12-21
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        相关资源
        最近更新 更多