結合モデルで属性を設定する問題に頭を悩ませていますか?
私のモデル:
class Contract < AR::Base
has_many :codelines
has_many :codes, :through => :codelines
accepts_nested_attributes_for :codes
attr_accessible :codes_attributes, :codes; :authnum, :st_date, :end_date
end
class Codeline < AR::Base
belongs_to :contract
belongs_to :code
units_alloc ...... this is the attribute I would like to set
end
class Code < AR::Base
has_many :codelines
has_many :contracts, :through => :codelines
end
app / controllers/contracts_controller.rbの新しいアクション
def new
@contract = Contract.new
@contract.codes.build
end
app / views / Contracts/_fields.html.hamlにある私のビューの部分
<fieldset><legend>Enter Billing Code Details</legend>
= f.fields_for :codes do |ff|
.field
= ff.label :name, "Code Name"
%br/
= ff.text_field :code_name
.field
.
.
= f.fields_for :codelines do |ff|
.field
= ff.label :name, "Units Alloc"
%br/
= ff.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10
</fieldset>
Railsガイドを読んだり、railscast#196と#197を見て、インターネット上でネストされた属性を調べたりすると、app / controllers/contracts_controller.rbの新しいアクションの@contract.codes.build行がビルドされただけではないことがわかりました。コードオブジェクトですが、コードラインオブジェクトも作成しました。app / controllers / Contracts_controller.rbの新しいアクションを上記のように残しておくと、まさにそれが起こります。私のコードラインテーブルは次のように入力されます。
id contract_id code_id units_alloc
1 1 1 .... @contract.codes.build
しかし、私の見解を見ると、実際にunits_allocを設定したいと思います。この行は、コードラインモデルにあるため、 @contract.codes.buildからunits_allocにアクセスできません。app / controllers / Contracts_controller.rbの新しいアクションに@contract.codelines.buildを追加しました。これで、units_allocがビューに表示され、設定できるようになりました。しかし、今ではコードラインテーブルに2つの行があります。1つは@contract.codes.buildの結果であり、コードオブジェクトとコードラインオブジェクトの両方がビルドされ、2番目の行は@ Contract.codelines.buildの結果であり、私のコードラインテーブルは次のとおりです。
id contract_id code_id units_alloc
1 1 1 .... @contract.codes.build
2 1 80.00 .... @contract.codelines.build
コードオブジェクトとコードラインオブジェクトの両方がビルドされる@contract.codes.buildで指定された最初のビルドを介して、units_allocにアクセスできるようにするべきではありませんか?
この問題についての私の理解が正しいかどうか誰かが知っていますか、それともすべてが明らかになるリソースを教えていただけますか?
後から考えたように、コードラインを使用してコードオブジェクトを作成しましたが、同じ結果が得られました。
提案をありがとう。
更新 コードラインテーブルに、関連するすべてのIDが次のように設定されたレコードを1つだけ含めることができます。
私のコンソール:
@contract = Contract.new(authnum: "900700", st_date: "2012-01-01", end_date:
"2012-30-06")
@contract.save
@code = Code.new(code_name: "S-5463", status: "Active", description:
"This and That")
@code.save
@codeline = @code.codelines.build(:units_alloc => "80.00", :contract => @contract)
@codeline.save
@codeline
=> #<Codeline id: 91, contract_id: 64, code_id: 54, units_alloc: 80.00>
pgadmin3を使用して、コードラインテーブルを確認すると、次の1つのレコードのみが取得されます。
id contract_id code_id units_alloc
91 64 54 80.00
ここでのテストは、contracts_controller new/createアクションを取得して同じことを行うことです。