的產品型號:表創建行與2人
class Usdzar < ActiveRecord::Base
has_many :smoothings
has_many :smoothvals, through: :smoothings
end
class Smoothval < ActiveRecord::Base
has_many :smoothprices
has_many :usdzars, through: :smoothings
end
class Smoothing < ActiveRecord::Base
belongs_to :usdzar
belongs_to :smoothval
accepts_nested_attributes_for :smoothval
accepts_nested_attributes_for :usdzar
before_save :create_smoothings
def create_smoothings
smoothval = Smoothval.find(smoothval_id)
1.upto(Usdzar.count) do
Smoothing.create!(
usdzar_id => usdzar.id,
smoothval_id => smoothval.id,
smprice => 99
)
end
end
使用的光滑控制器我從視圖操作設置smoothval從該表中的項的值,然後希望在執行計算價格在usdzar表中的每一行。我想要插入到平滑表中的輸出。每個價格ID都應該以fval和sval計算的smprice id結束。
我的方法是一個測試只是爲了讓循環工作,但它是失敗的。
遷移:
class CreateSmoothings < ActiveRecord::Migration
def change
create_table :smoothings do |t|
t.decimal :smprice, :precision => 8, :scale => 5
t.references :usdzar, index: true, foreign_key: true
t.references :smoothval, index: true, foreign_key: true
t.timestamps null: false
end
add_index :smoothings, :smprice
end
end
class CreateSmoothvals < ActiveRecord::Migration
def change
create_table :smoothvals do |t|
t.decimal :fval, :precision => 2, :scale => 0
t.decimal :sval, :precision => 2, :scale => 0
t.string :name
t.string :nickname
t.timestamps null: false
end
add_index :smoothvals, :name
end
end
class CreateUsdzars < ActiveRecord::Migration
def change
create_table :usdzars do |t|
t.date :day
t.decimal :price, :precision => 8, :scale => 5
t.decimal :delta, :precision => 8, :scale => 5
t.timestamps null: false
end
add_index :usdzars, :day
add_index :usdzars, :price
end
end
'本地主機:3000 /的光滑/新'(我選擇smoothval被用來從DD列表進行計算:
<%= form_for(@smoothing) do |f| %>
<% if @smoothing.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@smoothing.errors.count, "error") %> prohibited this smoothing from being saved:</h2>
<ul>
<% @smoothing.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :smoothvals %><br>
<%= f.collection_select :smoothval_id, Smoothval.all, :id, :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
提交當我得到:
undefined method `id' for nil:NilClass
Smoothing.create!(
usdzar_id => usdzar.id,
smoothval_id => smoothval.id,
smprice => 99
)
我有很強的PARAMS:
params.require(:smoothing).permit(:smprice, :usdzar_id, :smoothval_id, :usdzars_attributes => [:id, :price, :delta])
有人可以給我一個想法,爲什麼它這樣做,以及更好的方法可能是什麼?
感謝您的幫助 – giarcnappel
我的答案解決了您的問題嗎? –
這工作,但所有項目都輸入了零值。我認爲我的問題就像你說的讓變量聲明一樣,然而變量是循環的一個函數,所以它不是來自視圖,而是需要在模型中完成。 usdzar_id => usdzar.id, smoothval_id => smoothval.id, smprice => 99這不會聲明和分配? – giarcnappel