Deviseとbootstrapのインストール2

2016/01/10 | Ruby on Rails

前回Deviseとbootstrapのインストールを行いましたが、その続きです。

これに投稿機能を付けてみようと思います。

scaffoldで投稿機能を追加

$ rails g scaffold post tittle:string content:text user_id:integer
会員登録してくれたユーザーに紐づけするためuser_id:integerも一緒に入れます。tittleはstring、contentはtext、user_idはintegerで型の指定をします。

$ rake db:migrate
これでurl/postsにアクセスすると投稿機能が追加されているはずです。

ユーザーとの紐づけ

会員登録してもらったユーザーに投稿を紐付けします。
まず、ログインしないと投稿できないようにします。
[code lang=”rails” title=”app/controller/posts_controller.rb” highlight=”2″]
class PostsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
before_action :set_post, only: [:show, :edit, :update, :destroy]
[/code]
indexとshowは除いてログインしていないとアクセス出来ないようにします。

[code lang=”rails” title=”app/controller/posts_controller.rb” highlight=”3″]
def create
@post = Post.new(post_params)
@post.user = current_user

respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: ‘Post was successfully created.’ }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
[/code]
user_idはcurrent_userになるので削除します。
[code lang=”rails” highlight=”9″]
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:tittle, :content)
end
[/code]

ユーザーと投稿は1対多になるのでそれを追加。ついでにバリデーションも追加しておきます。
[code lang=”rails” title=”app/models/posts_controller.rb” highlight=”2,4″]
class Post < ActiveRecord::Base
belongs_to :user

validates :user_id, presence: true
end

[/code]
[code lang=”rails” title=”app/models/users_controller.rb” highlight=”7″]
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

has_many :posts, dependent: :destroy
end
[/code]
formのuser_idを非表示にします。
[code lang=”html” title=”app/views/posts/_form.html.erb” highlight=”2″]
<div class="field">
<%= f.hidden_field :user_id %>
</div>
[/code]
Devise-Test-form2

これでログインして記事を投稿すると、user_idが取得されて投稿されます。
Devise-Test-list

カスタマイズ

これにカスタマイズを更にしてみます。

リダイレクト

$ rails g controller Pages index
Pageのcontrollerを作成し、
[code lang=”rails” title=”config/routes.rb” highlight=”2″]
root to: ‘pages#index’
[/code]
に変更。
[code lang=”rails” title=”pages_controller.rb” highlight=”3-5″]
class PagesController < ApplicationController
def index
if current_user
redirect_to :controller => ‘posts’
end
end
end
[/code]
これでゲストがrootにアクセスした場合にはpages/indexへ、ログインした後にrootにアクセスした場合はrootからpostsにリダイレクトされます。

自分の投稿したものだけを表示したい場合

[code lang=”rails” title=”posts_controller.rb” highlight=”2,8″]
def index
@posts = current_user.posts.all
end

private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = current_user.posts.find(params[:id])
end
[/code]
これに変更すればindexに自分の投稿のみ表示されます。

連記事

bundle exec cap production puma:nginx_config

2024/03/26 | Ruby on Rails

cd /etc/nginx sudo mkdir sites-available これをしてから % bundle exec cap production puma:nginx_config...

Amazon Linux 2023にmysqlをインストール

2024/03/26 | Ruby on Rails

Amazon Linux 2023でmysqlのインストール方法 $ sudo yum localinstall -y https://dev.mysql.com/get/mysql80-commu...

simple_formのcollectionのselectを任意の値で並べる方法

2020/02/21 | Ruby on Rails

Railsのsimple_formでorder作成時にproduct_nameとproduct_codeを持つproductをproduct_codeで並べ替える方法です。 ちょっとハマったので...

enumで特定の値を除外する場合

2018/12/20 | Ruby on Rails

enumで選択肢が2つある場合 # models/blog.rb class Blog < ApplicationRecord   enum status: { published...

pdf出力

2017/06/30 | Ruby on Rails

railsでpdfに出力 #gemfile gem 'wkhtmltopdf-binary' gem 'wicked_pdf' #config/initializers/wicked_...