0

我想知道如何去有一個submit按鈕,將更改布爾屬性,而不是使用單選按鈕。Rails提交按鈕爲布爾attribbute

作爲一個例子,如果我在Post#index頁面上顯示'已發佈'和'未發佈'文章帖子的列表,並且我想要一個名爲'發佈'的按鈕,將Post模型上的:is_published字段設置爲true。

我使用on Rails的3.2.13

我想在Post控制器strong_parameters我會

def index 
    @post = Post.recent 
end 

def update 
    @post = Post.find_by_slug(params[:id]) 
    if params[:publish_button] 
    @post.is_published = true 
    @post.save 
    redirect_to root_path 
    end 
end 

private 

def post_params 
    params.require(:person).permit(:body, :publish_button) 
end 

在我Post#index鑑於我有一個form_for<%= f.submit 'Publish', name: publish_button %>

這裏是Post#index的視圖

<%= form_for @post do |f| %> 
    <div class="field"> 
    <%= f.label :body %><br /> 
    <%= f.text_field :body %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    <%= f.submit_tag 'Publish Post', name: 'publish_post' %> 
    </div> 
<% end %> 

簡單的模型如下

class Post < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 

    scope :recent, -> { order('updated_at DESC') } 
end 

但我發現了的Required parameter missing: post

由於錯誤提前。

更新 我已經添加了與該問題對應的模型和視圖。我希望它有幫助。

+1

添加視圖和模型將有助於幫助你。 – wintermeyer

+0

嗨,我已添加模型和視圖。謝謝你或你的意見。 –

回答

0

將您的值作爲隱藏字段傳遞,例如

= form_for @post do |f| 
    = f.hidden_field :is_published, value: "1" 
    = f.submit "Publish" 

,如果你希望它是內嵌像button_to,給它button_to類:

= form_for current_user.profile, html: { class: 'button_to' } do |f| 
    ...