我想知道如何使用submit
按钮来更改布尔属性,而不是使用单选按钮。
例如,如果我在Post#index
页面上显示"已发布"one_answers"未发布"文章帖子的列表,并且我想要一个名为"发布"的按钮,将Post
模型上的:is_published字段设置为true。
我在Rails上使用strong_parameters 3.2.13
我在想,在Post
控制器中,我会有
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
视图中,我有一个具有<%= f.submit 'Publish', name: publish_button %>
的form_for
这是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
的错误
提前谢谢。
更新我添加了一个与问题相对应的模型和视图。我希望它能有所帮助。
将值作为隐藏字段传递,例如
= form_for @post do |f|
= f.hidden_field :is_published, value: "1"
= f.submit "Publish"
如果你想让它像button_to一样内联,就给它一个button_toclass:
= form_for current_user.profile, html: { class: 'button_to' } do |f|
...