我有两个表用户和收入。用户具有id列,而Income具有引用User的id列的user_id的外键。该关联已在模型中创建:用户将拥有收入和收入属于用户。我希望收入模型中的new.html.erb提交一个新的收入项,并将其外键设置为会话的当前用户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" %>
答案 0 :(得分:1)
尝试
<%= 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 %>