LoginSignup
3
3

More than 5 years have passed since last update.

Railsで、あるモデルに関連付けて別のモデルを保存するには

Last updated at Posted at 2013-03-31

例:現在のUserに関連付けられたRecordを保存する

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user

  private
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end
app/controllers/record_controller.rb
  def create
    #@record = Record.new(params[:record])
    @record = current_user.records.new(params[:record])
app/views/records/_form.html.erb
<%= form_for(@record) do |f| %>
  <% if @record.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@record.errors.count, "error") %> prohibited this record from being saved:</h2>

      <ul>
      <% @record.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <!--<div class="field">
    <%#= f.label 'user id' %><br />
    <%#= f.text_field :user_id %>
  </div>-->
  <div class="field">
    <%= f.label :weight %><br />
    <%= f.text_field :weight %>
  </div>
  <div class="field">
    <%= f.label :memo %><br />
    <%= f.text_area :memo %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

ブログやってます:PAPA-tronix !

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