我在创建帖子时设置 user_id 时遇到问题
def create
@post = Post.new(post_params)
@post.user_id = session[:id]
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
我得到的错误特别是undefined method 'username' for nil:NilClass
在重定向到显示操作时。查看数据库显示未设置 user_id。
我还尝试将 user_id 作为隐藏字段传递。但这也不起作用(查看日志显示由于某种原因甚至没有通过隐藏字段)。
会欣赏正确方向的一点,
谢谢 !
编辑:这里要求的是显示控制器
def show
@post = Post.find(params[:id])
@original_id = params[:original_id]
@comment = Comment.new
end
<%= form_for [:admin, @post] do |f| %>
<% 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">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.label :category %><br>
<%= f.text_field :category %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
路线:
根'帖子#index'
resources :posts do
resources :comments, shallow: true
end
resources :users, only: [:create]
#Posts
get "/meta", to: "posts#meta"
#User Routes
get "/signup", to: "users#new"
get "/success", to: "users#index"
#login Routes
get "/login", to: "sessions#login"
post "/sessions/login_attempt", to: "sessions#login_attempt"
#session routes
get "/sessions/home", to: "sessions#home"
get "/sessions/logout", to: "sessions#logout"
#admin routes
#resources :posts, module: 'admin', except: [:show, :index]
namespace :admin do
root 'posts#new'
resources :posts, except: [:show, :index]
end