0
ユーザーとインカムの2つのテーブルがあります。ユーザーにはid列があり、IncomeにはユーザーID列を参照するuser_idの外部キーがあります。この関連付けはモデルで作成されました。ユーザーは所得があり、所得はbelongs_toです。私は所得モデルのnew.html.erbに新しい収入項目を提出し、ユーザーのIDをフォームに入れずにセッションの現在のユーザーのIDにその外部キーを設定するようにします(つまり、ユーザーは自分のアカウントでサインインする必要があります)。ここでフォームに現在のセッションのユーザーIDを生成します。
は自分のアプリケーションのコントローラである:ここで
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user #make the private method to be accessible for the view
end
end
は収入モデルのための私のnew.html.erbです:
<h1>Add New Income</h1>
<div class="field">
<%= form_tag %>
<%= label_tag :title %>
<%= text_field :title, params[:title] %>
<%= label_tag :amount %>
<%= number_field :amount, params[:amount] %>
<br>
<% if current_user %>
User ID:<%= current_user.id %>
User Name: <%= current_user.user_name %>
<% :user_id = current_user.id%>
<% end %>
<%= submit_tag "Submit" %>