2017-03-14 38 views
0

我在添加has_manybelongs_to時遇到問題,我的代碼就是這樣。添加關聯後會變成錯誤[Ruby on Rails]

模型/ blog_post.rb

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

     mount_uploader :image, ImageUploader 
    end 

模型/ user.rb

class BlogPost < ApplicationRecord 

belongs_to :user, inverse_of: :blog_posts 
end 

控制器/ blog_posts_controller.rb

class BlogPostsController < ApplicationController 
    before_action :authenticate_user! 
    def new 
    @bp = BlogPost.new 
    end 

    def create 
    @bp = BlogPost.new 
    @bp.user_name = current_user 
    @bp.title = params[:blog_post][:title] 
    @bp.content = params[:blog_post][:content] 
    @bp.save 
    redirect_to blog_post_path(@bp.id) 
    end 

    def show 
    @bp = BlogPost.find(params[:id]) 
    end 

def destroy 
    @bp = BlogPost.find(params[:id]) 
    @bp.destroy 
    redirect_to root_path(@bp) 
    end 
end 

視圖/ blog_posts/new.html.slim

h1 Let's post your article! 

= form_for @bp do |f| 
    h2 title 
    = f.text_field :title 
    h2 content 
    = f.text_area :content 
    br 
    = f.submit "Submit" 
a href="/" Home 

的意見/ blog_posts/show.html.slim

h2 name 
p = @user.user_name 
h2 title 
p = @bp.title 
h2 content 
p = @bp.content 
a href="/"Home 

,我得到這個錯誤... ActionController::UrlGenerationError in BlogPostsController#create``No route matches {:action=>"show", :controller=>"blog_posts", :id=>nil} missing required keys: [:id]

是否有解決這個問題的任何想法?

回答

0

好像BlogPost不會被保存,這就是爲什麼它與id = nil

重定向它嘗試的代碼更改爲

if @bp.save 
    redirect_to blog_post_path(@bp.id) 
else 
    render :edit 
end 
+0

謝謝你的快速回復!但它不工作... –

+0

謝謝你給我一個建議!我感到非常可恥,因爲我沒有在我的blog_posts表上添加user_id ......之後,它就起作用了! –

0

嘗試重定向到新創建的對象@bp,你不真正需要blog_post_path(@ bp.id) 以下也應該可以正常工作

def create 
    @bp = BlogPost.new 
    @bp.user_name = current_user 
    @bp.title = params[:blog_post][:title] 
    @bp.content = params[:blog_post][:content] 

    respond_to do |format| 
     if @bp.save 
     redirect_to @bp, notice: 'Blog Post was successfully created.' 
     else 
     render :edit 
     end 
    end 
    end 

但是,也可能是您的路由設置不正確,如果上述操作不起作用,請分享您的config/routes.rb文件以查看它是如何定義的。

你也可以在你的文件中定義它像這樣

的config/routes.rb中

resources :blog_posts 
+0

謝謝你給我一個建議!我感到非常可恥,因爲我沒有在我的blog_posts表上添加user_id ......之後,它就起作用了! –

+0

您還可以嘗試在腳手架上讀取生成的文件的結果。它給出了所需的基本事物的一些想法。很高興知道如何從頭開始做,但作爲參考或例子也很好「rails生成scaffold ModelName的東西:string something:string」 – rubencp