Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails上的if-else布尔/复选框_Ruby On Rails_Ruby_Boolean - Fatal编程技术网

Ruby on rails Rails上的if-else布尔/复选框

Ruby on rails Rails上的if-else布尔/复选框,ruby-on-rails,ruby,boolean,Ruby On Rails,Ruby,Boolean,我有一个博客应用程序。每篇文章在出现在头版之前,都需要先选中“已发布”。我需要在表格上打个复选框 在django,我可以通过以下方式实现这一点: models.py views.py 如何在Rails中实现这一点 ----------更新--------- [已解决] 一步一步- 添加新迁移: rails g migration add_published_to_posts published:boolean 在迁移文件上,将发布的默认值设置为False class AddPublishedT

我有一个博客应用程序。每篇文章在出现在头版之前,都需要先选中“已发布”。我需要在表格上打个复选框

在django,我可以通过以下方式实现这一点:

models.py views.py 如何在Rails中实现这一点

----------更新---------

[已解决]

一步一步-

添加新迁移:

rails g migration add_published_to_posts published:boolean
在迁移文件上,将发布的默认值设置为
False

class AddPublishedToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :published, :boolean, default: false
  end
end
在邮政署署长:

 def index
   @posts = Post.where(published: true)
 end
 def update
   @post = Post.find(params[:id])

   if @post.update(params[:post].permit(:title, :body, :published))
     redirect_to @post
   else
     render 'edit'
   end
 end
添加<代码>:发布<代码>控制站上的许可证:

 def index
   @posts = Post.where(published: true)
 end
 def update
   @post = Post.find(params[:id])

   if @post.update(params[:post].permit(:title, :body, :published))
     redirect_to @post
   else
     render 'edit'
   end
 end

您可以通过迁移在
posts
表中添加已发布的布尔列

rails g migration add_published_to_posts published:boolean
然后,在生成的迁移文件上,为已发布列设置
default:false

class AddPublishedToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :published, :boolean, default: false
  end
end

您可以使用此作用域通过
Post在视图中拉取已发布的博客文章。已发布的
和未发布的博客文章通过
Post。未发布的

您希望复选框自动提交(如按钮)并立即发布,还是与表单的其余部分一起提交?您的意思是
Post.where(published:true)
作为查询还是您指的是复选框助手?@JacobVanus我想在单击提交按钮之前先选中复选框。默认情况下,它应该是
False
。谢谢大家!@塞巴斯蒂安帕尔马是的,作为一个疑问。非常感谢。要将其设为默认值,您可以将迁移上的默认值设为false,和/或在复选框中也设为false。谢谢@sa77我遵循您的代码,但现在我的所有帖子都隐藏/不显示在索引页上。这是呈现复选框表单的正确方法:
?因为它似乎不起作用,即使我检查了
发布的
,它仍然没有显示。如何在控制器上进行过滤,而不是在视图上进行过滤?是的。。检查您的
posts\u controller.rb
。。您必须添加
:published
作为允许的强参数,以允许在表单submitGreat上更新它!我忘了那部分。谢谢你,你太棒了@sa77
class AddPublishedToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :published, :boolean, default: false
  end
end
# app/models/post.rb
class Post < ActiveRecord::Base
  scope :published, -> { where(published: true) }
  scope :unpublished, -> { where(published: false) }
end