Reputation: 1370
I have two tables Users and Incomes. User has an id column and Income has a foreign key of user_id that is referencing User's id column. The association has been created in the model: User will has_many incomes and income belongs_to user. I want the new.html.erb in the income model to submit a new income item and set its foreign key to the session's current user's id without the user put in id in the form(that means user must sign in with his/her account).
Here is my application controller:
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
Here is my new.html.erb for the income model:
<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" %>
Upvotes: 0
Views: 1154
Reputation: 574
Try
<%= form_for(@income, :html =>{:class => "form "}) do |f| %>
<%= 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 %>
<%= f.hidden_field :user_id, value: current_user.id%>
<% end %>
<%= submit_tag "Submit" %>
<% end %>
Upvotes: 3