我有以下内容:属于/有很多关系
客户端有许多报告和报告属于客户端。
但是,在创建报告时,它并未将client_id分配到数据库中,但不知道为什么?
我在这里做错了什么?
客户端模型
class Client < ActiveRecord::Base
has_many :reports, :dependent => :destroy
end
报表模型
class Report < ActiveRecord::Base
has_attached_file :report
belongs_to :client
end
客户机控制器(更新)
# PUT /clients/1
# PUT /clients/1.json
def update
@client = Client.find(params[:id])
respond_to do |format|
if @client.update_attributes(params[:client])
format.html { redirect_to [:admin,@client], :notice => 'Client was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @client.errors, :status => :unprocessable_entity }
end
end
end
报告控制器(创建)
# POST /reports
# POST /reports.json
def create
@report = Report.new(params[:report])
@report.client_id = params[:client][:client_id]
respond_to do |format|
if @report.save
format.html { redirect_to '/admin/clients', :notice => 'Report was successfully created.' }
format.json { render :json => @report, :status => :created, :location => @report }
else
format.html { render :action => "new" }
format.json { render :json => @report.errors, :status => :unprocessable_entity }
end
end
end
客户端,编辑,查看
<%= form_for([:admin, @client.reports.build]) do |f| %>
<label class="formlabel">Report Upload</label>
<%= f.file_field :report, :class=>"text-input small-input" %>
<div class="actions">
<br />
<%= f.submit 'Upload', :class => 'button' %>
</div>
<% end %>
援助将不胜感激!
你可以验证是否为'params [:client] [:client_id]'设置了一个值吗?如果不是这样,那么你可以通过将'@ client.reports.build'设置为nil来取消它的工作。 AFAIK当使用'.build'方法初始化子对象时,它应该在运行'.save'时为你自动设置foreign_key。 – Noz
您可以向我们展示您的创建/更新操作的参数吗? – Noz
不知道我是否理解你的意思,更新操作是否在 – Clay