我有两个模型:用户和描述。所有用户都有一个描述,所有描述都属于用户。我创建了一个创建描述的表单,但是当我尝试在视图中检索描述数据时,我做不到。我检查了我的数据库,并且描述表的user_id列没有更新。我认为这应该通过has_one / belongs_to关系自动发生。如何解决这个问题,以便user_id字段自动填充用户的ID?
这是我的用户模型:
class User < ActiveRecord::Base
has_one :description
accepts_nested_attributes_for :description
end
这是我的描述模型::
class Description < ActiveRecord::Base
belongs_to :user
end
这是我的描述控制器:
class DescriptionsController < ApplicationController
def new
@description = Description.new
@current = current_user.id
end
def create
#Description.create(description_params)
@description = Description.create(description_params)
redirect_to student_path
end
def index
end
private
def description_params
params.require(:description).permit(:skills, :looking_for, :my_idea, :user_id)
end
end
以下是观点:
<div class="span6 offset3 text-center">
<h1>Edit your information</h1>
<%= simple_form_for @description do |f| %>
<%= f.input :skills %>
<%= f.input :looking_for, :label => 'What help do you need?' %>
<%= f.input :my_idea %>
<%= f.input :user_id, :as => :hidden, :value => @current %>
<%= f.submit "Save", :class => "btn btn-primary btn-large" %>
<% end %>
</div>
我尝试从已接受的参数中删除user_id - 这没有任何作用。我也尝试使用隐藏字段传递user_id - 这不起作用,但我也不认为它应该是necesarry,我不认为这是解决问题的正确方法。
答案 0 :(得分:1)
如果您使用的是accepts_nested_attributes_for
,我们的想法是您将Description
模型的属性作为部分提交给User
模型。这似乎不是你在这里做的。
如果您不想这样做,则应删除该行并在控制器中执行
current_user.build_description(description_params)
(如果你想一次初始化/保存所有内容,你可以使用#create_description
。)
例如
def create
@description = current_user.create_description(description_params)
redirect_to student_path
end
有关这些has_one
方法的文档,请参阅Active Record Associations guide。