new.html.erb
<h3>Add post</h3>
<%= form_tag :controller=>'posts', :action=>'create' do %>
<%= label :q, :Title %>
<%= text_field :data, :title, :class => :addtextsize %><br/>
<%= label :q, :Content %>
<%= text_area :data, :content, :rows=>10 , :class => :addtextarea %><br/>
<%= label :q, :Category %>
<%= select :data, :category_id, @categories_select %><br/>
<%= label :q, :Tags %>
<%= text_field :data, :tags, :class => :addtextsize %><br/>
<%= label :q, :Submit %>
<%= submit_tag "Add Post" %>
<% end %>
创建PostController.rb的动作
def create
@categories_select = Category.all.collect {|c| [ c.category_name, c.id ] }
@addpost = Post.new params[:data]
if @addpost.save
flash[:notice] = "Post has been saved successfully."
redirect_to posts_path
else
flash[:notice] = "Post can not be saved, please enter information."
render :new
#redirect_to new_post_path
end
end
获取users.id我需要将其插入posts表中。我该怎么办?
帖子表
Table "public.posts"
Column | Type | Modifiers
-------------+------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(100) | not null
content | character varying(500) | not null
created_at | date |
updated_at | date |
tags | character varying(55) | not null default '50'::character varying
category_id | integer | not null default 1
user_id | integer |
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
答案 0 :(得分:3)
Devise提供了一个名为current_user
的辅助方法,您可以使用它来获取经过身份验证的用户。因此,您可以在表单中输入隐藏的文本输入,如下所示:
<%= hidden_field_tag :user_id, current_user.id %>
这样就可以将其传递到您的params
。
另一种选择是在create
方法中手动添加它:
def create
@categories_select = Category.all.collect {|c| [ c.category_name, c.id ] }
@addpost = Post.new params[:data]
@addpost.user_id = current_user.id
if @addpost.save
flash[:notice] = "Post has been saved successfully."
redirect_to posts_path
else
flash[:notice] = "Post can not be saved, please enter information."
render :new
#redirect_to new_post_path
end
end