FavoritesController #create中的ActiveRecord :: UnknownAttributeError

时间:2015-07-31 14:32:59

标签: ruby-on-rails-4 activerecord

我为收藏夹获取未知属性'post'。当我在表中缺少列时,通常会发生此错误。错误是说明这部分是问题所在:favorite = current_user.favorites.build(post:post)。但是不应该有另一个名为post的专栏。我是否有另一套嵌套的参数我可能会错过或许在某些东西下分层?或者我的参考完整性不正确?

错误屏幕截图 unkown_attribute_error

Favorites_controller.rb文件

class FavoritesController < ApplicationController

  def create
   post = Post.find(params[:post_id])
   favorite = current_user.favorites.build(post: post)

     if favorite.save
       flash[:notice] = "This post is now favorited."
       redirect_to [post.topic, post]
    else
      flash[:error] = "There was an error favoriting you post.  Please try again."
      redirect_to [post.topic, post]
    end
    end



   end

收藏夹架构

create_table "favorites", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer  "user_id" 
t.integer  "post_id"
end

后置控制器

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :votes
  has_one :summary
  belongs_to :user #means the post table has the user table's primary k ey in it
  belongs_to :topic
  has_many :favorites

#has_one :summary
mount_uploader :avatar, AvatarUploader
#default_scope {order('created_at DESC')}
default_scope {order('rank DESC')}

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



 def create_vote
 # self == post
   user.votes.create(value: 1, post: self)
 end


 def markdown_title
   (render_as_markdown).render(self.title).html_safe
 end


 def markdown_body
  (render_as_markdown).render(self.body).html_safe
 end

 def up_votes
  votes.where(value: 1).count
 end

 def down_votes
  votes.where(value: -1).count
 end

 def points
  votes.pluck(:value).sum
 end

 def update_rank
  age_in_days = (created_at - Time.new(1970,1,1)) / (60 * 60 * 24) #1      day in seconds
  new_rank = points + age_in_days

update_attribute(:rank, new_rank)
 end

private

 def render_as_markdown
  renderer = Redcarpet::Render::HTML.new
  extensions = {fenced_code_blocks: true}
  redcarpet = Redcarpet::Markdown.new(renderer, extensions)
  return redcarpet
 end
end

发布表架构

create_table "posts", force: :cascade do |t|
t.string   "title"
t.text     "body"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id"
t.integer  "topic_id"
t.string   "avatar"
t.float    "rank"
end

收藏路线

rake routes | grep -i favorites
      post_favorites POST   /posts/:post_id/favorites(.:format)                  favorites#create
       post_favorite DELETE /posts/:post_id/favorites/:id(.:format)              favorites#destroy

1 个答案:

答案 0 :(得分:2)

这一行

favorite = current_user.favorites.build(post: post)

应该是

favorite = current_user.favorites.build(post_id: post.id)

因为post_id表格中favourites不是post