我有以下內容:屬於/有很多關係
客戶端有許多報告和報告屬於客戶端。
但是,在創建報告時,它並未將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