我需要将user_id存储在posts表中(对于每个新帖子)。我将表单中的user_id作为hidden_field传递。什么是从控制器本身获取user_id的替代方法。
控制器中的
def create
@post =@topic.posts.new(post_params).save
end
发布模型
class Post < ApplicationRecord
belongs_to :topic, counter_cache: true
belongs_to :user
has_and_belongs_to_many :users # to maintain read and unread status for the posts
has_many :comments , dependent: :destroy
has_many :ratings , dependent: :destroy
has_and_belongs_to_many :tags
end
形式
<%= form_for [@topic, @post],remote: true,html: { multipart: true} do |form| %>
<div class="field">
<%= form.label :author %>
<%= form.text_field :author, :value => current_user.email %>
</div>
<%= form.label :content %>
<%= form.text_area :content, id: :post_content, autofocus: true %>
<!--<%= form.hidden_field :user_id %>-->
<div class="field">
<%=form.label :image%><br>
<%=form.file_field :image %>
</div>
<%= form.fields_for :tags do |a|%>
<div class="field">
<%= a.label :tag_name %>
<%= a.text_area :tag_name %>
</div>
<% end %>
<div class="field">
<%= form.label "select tag" %>
<%= form.collection_select(:tag_ids, Tag.all, :id, :tag_name, {}, {:multiple => true, :size => 10, :prompt_text => "select tag"}) %>
</div>
<div class="submit">
<%= form.submit %>
</div>
<% end %>
答案 0 :(得分:0)
您可以在控制器中使用current_user
,如下所示
def create
@topic.posts.new(post_params).save
end
private
def post_params
params.require(:post).permit(...).merge(user: current_user)
end
或
def create
@topic.posts.new(post_params.merge(user: current_user)).save
end