2
3

More than 3 years have passed since last update.

hidden_fieldのわかりやすい例

Last updated at Posted at 2019-05-15

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
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3