2017-12-30 16 views
0

私は自分のRailsブロックに問題があります。私がコメントセクションを実装した後、私はもはや投稿を作成することができません。コンソールは私にロールバックトランザクションを与えます。だから私はしたRailsロールバックトランザクション

p = Post.new 
p.valid? # false 
p.errors.messages 

私はユーザー:user=>["must exist"]のいくつかの検証の問題があるようだ。しかし、私がコメントを実装する前に、それはうまくいった。誰かが私を助けることができますか?

User.rb

class User < ApplicationRecord 
    has_many :posts 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

Post.rb

class Post < ApplicationRecord 
    belongs_to :user 
    has_many :comments, dependent: :destroy 

    validates :title, presence: true, length: {minimum: 5} 
    validates :body, presence: true 


    has_attached_file :image #, :styles => { :medium => "300x300>", :thumb => "100x100>" } 
    validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 
end 

ポスト移行

class CreatePosts < ActiveRecord::Migration[5.1] 
    def change 
    create_table :posts do |t| 
    t.string :title 
    t.text :body 

    t.timestamps 
    end 
    end 
end 

Post_controller

class PostsController < ApplicationController 
    def index 
    @posts = Post.all.order("created_at DESC") 
    end 

    def new 
    @post = Post.new 
    end 

    def create 
    @post = Post.new(post_params) 

    if @post.save 
     redirect_to @post 
    else 
     render 'new' 
    end 
    end 

    def show 
    @post = Post.find(params[:id]) 
    end 

    def edit 
    @post = Post.find(params[:id]) 
    end 

    def update 
    @post = Post.find(params[:id]) 

    if @post.update(post_params) 
     redirect_to @post 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    @post = Post.find(params[:id]) 
    @post.destroy 

    redirect_to posts_path 
    end 

    private 

    def post_params 
    params.require(:post).permit(:title, :body, :theme) 
    end 
end 
+0

Rails 5を使用しているので、デフォルトで 'belongs_to'という関連付けが必要です。したがって、投稿を作成するときには、ユーザーにも提供する必要があります。 –

+0

多分私はactive_adminを使用していると言って、同様に考案する必要があります。以前はうまくいったからです。私はユーザを提供していると思った。 – minennick

+0

あなたの 'PostsController'でエラーが発生していますか?もしそうなら、コードを共有することはできますか? –

答えて

0

あなたがあなたの記事コントローラの下に作成する方法でそのポストにユーザーを割り当てる必要がポストを作成しています。あなたはこのようなものを試すことができます。デフォルトでは

def create 
    if current_user 
    @post.user_id = current_user.id 
    end 

    ## More create method stuff 
end 

は、belongs_to関連して、ユーザは、そうでない場合、あなたがポストを作成することができませんポストを作成するために必要です。見た目からは、createメソッドでその投稿にユーザーを割り当てるものはありません。

+0

を超えていますif文で試してみましたが、何も変わりませんでした。それはアクティブな管理者と関係がありますか? – minennick

+0

'belongs_to'関連の後に' optional:true'を追加してみてください。 'belongs_to:user、optional:true' –

+0

'オプション:true'を修正しました。大いに感謝する。何が「オプション」なのかを理解するだけです。本当ですか? – minennick

関連する問題