我需要将 user_id 存储在帖子表中(对于每个新帖子)。我将表单中的 user_id 作为 hidden_field 传递。从控制器本身获取 user_id 的替代方法是什么。
在控制器中
def create
@post [email protected](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 %>
您可以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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句