使用current_user连接post时出现“unknown attribute:user_id”

时间:2012-09-10 19:38:37

标签: ruby-on-rails ruby ruby-on-rails-3 attributes devise

首先,我对编程和Ruby on Rails很陌生,所以请详细描述更正,谢谢。 : - )

当我在我的博客系统中尝试将新帖子连接到current_user时,我遇到了“未知属性:user_id” - 错误。

我还希望用户(创建帖子的用户)在帖子的显示页面上显示为帖子的创建者。 现在,您手动输入名称,但如何更改此名称,以便“名称”将成为“current_user”的“用户名”?

我试图搜索类似的主题,但经过一段时间的尝试,我自己无法解决问题。

应用/控制器/ posts_controller.rb

class PostsController < ApplicationController
before_filter :authenticate_user!

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

  # GET /posts/new
  # GET /posts/new.json
  def new
  ##  @post = Post.new
  ##  @post = current_user.posts.new(params[:post])
  @user = User.find(current_user)
  @post = @user.posts.new(params[:post])
  @post.save 

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.json
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end
end

应用/模型/ post.rb

class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title, :tags_attributes, :username

  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }

  has_many :comments, :dependent => :destroy
  has_many :tags

  before_create :username
  belongs_to :user

  accepts_nested_attributes_for :tags, :allow_destroy => :true,
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end

分贝/ schema.rb

ActiveRecord::Schema.define(:version => 20120904152633) do

  create_table "comments", :force => true do |t|
    t.string   "commenter"
    t.text     "body"
    t.integer  "post_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "comments", ["post_id"], :name => "index_comments_on_post_id"

  create_table "posts", :force => true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.text     "content"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "tags", :force => true do |t|
    t.string   "name"
    t.integer  "post_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "tags", ["post_id"], :name => "index_tags_on_post_id"

  create_table "users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "username"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name =>                                    "index_users_on_reset_password_token", :unique => true

end

应用/视图/帖/ index.html.erb

(...)

<table>
  <tr>
    <th style="width: 15%">Name</th>
    <th style="width: 20%">Title</th>
    <th>Content</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= post.title %></td>
    <td><%= post.content %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>

(...)

应用/视图/帖/ _form.html.erb

<% @post.tags.build %>
<%= form_for(@post) do |post_form| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </div>
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </div>
    <h2>Tags</h2>
  <%= render :partial => 'tags/form',
             :locals => {:form => post_form} %>
  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>

提前谢谢!

修改

我的users_helper.rb是空的,但在读完其他地方后,我补充说:

应用/助手/ users_helper.rb

module UsersHelper

alias_method :devise_current_user, :current_user
def current_user
  if params[:user_id].blank?
    devise_current_user
  else
    User.find(params[:user_id])
  end
end

end

而且,现在我收到此错误:路由错误 - 未定义方法current_user' for module UsersHelper'

配置/ routes.rb中

Blog::Application.routes.draw do
  devise_for :users

  resources :users do
    resources :posts
    resources :comments
  end

  resources :posts do
    resources :comments
  end

  resources :users

  get "home/index"

  get '/users/:id', :to => "users#show", :as => :user
  get "/:id", :to => "users#show", :as => :user

root :to => 'home#index'

end

1 个答案:

答案 0 :(得分:0)

就您提供的信息而言,似乎current_user方法未正确返回User对象。无论它返回什么,它都会返回一个没有user_id属性的对象。

向我们展示您的current_user方法(可能在用户帮助中),我们将能够为您提供更好的帮助。


除了我先前所说的,我认为你应该删除

@post.save 
respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @post }
end

来自帖子控制器中的new操作。

在Rails中,传统上,new操作仅生成表单的视图。 new操作与将数据保存到数据库无关。这将是create行动的工作。也许摆脱它可能会解决问题。