##hiddenでuser_idを送りたい時
<%= form.hidden_field :user_id, value:current_user.id %>
new.html.erb
<%= form_with(model: post, local: true) do |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 |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :comment %>
<%= form.text_field :comment %>
</div>
<%= form.hidden_field :user_id, value:current_user.id %> //ここ
<div class="actions">
<%= form.submit %>
</div>
<% end %>
ついでに
posts_controller.rb
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
private
def post_params
params.require(:post).permit(:comment, :user_id)
end
アソシエーション
user.rb
has_many :posts
post.rb
belongs_to :user, optional: true