0
我沒有被使用Rails的工作爲所有長期和我的工作有關創建博客。我想在後的形式與「公共及‘私人’,並有選擇當選擇私人擁有這個職位不顯示,除非用戶登錄。什麼是去這樣做的最好方法是什麼?發帖的私人Rails中
我沒有被使用Rails的工作爲所有長期和我的工作有關創建博客。我想在後的形式與「公共及‘私人’,並有選擇當選擇私人擁有這個職位不顯示,除非用戶登錄。什麼是去這樣做的最好方法是什麼?發帖的私人Rails中
您將一個新的布爾字段添加到您的posts
表:
rails generate migration add_published_to_posts published:boolean
添加旁邊的這個新文件:
class AddPublishedToPosts < ActiveRecord::Migration
def change
add_column :posts, :published, :boolean, default: 0
end
end
這樣,所有的職位都是「私有」(未出版)改變默認默認值爲1,如果你想要帖子是「公開」(publ被捨棄)。
遷移數據庫:
rake db:migrate
在你的類,你可以添加此範圍:
class Post < ActiveRecord::Base
default_scope { where(published: true) }
# or
scope :published, -> { where(published: true) }
end
在你的控制,加上類似的東西:
def index
# With default scope
@posts = Post.all
# With named scope
@posts = Post.published
end
添加新的領域到您的形式和voilá。
= form_for @post do |f|
# other fields
= f.check_box :published
似乎無法得到此工作。請原諒我的新手,但新的領域應該是什麼樣子?我在想我把它弄錯了。 – darkknight89
@ darkknight89我已經更新了我的答案。這很簡單。我希望這有幫助。 – backpackerhh
謝謝你的幫助。你是對的,這很容易,我意識到我的錯誤是一個我之前從未注意到的簡單錯字。 – darkknight89