有很多類似的主題,但它不幫助我。 有一個帳戶模型使用來自窗體中關聯模型的數據,Rails 3
class Account < ActiveRecord::Base
belongs_to :user
belongs_to :currency
attr_accessible :currency
accepts_nested_attributes_for :currency
end
我加入attr_accessible和accepts_nested_attributes_for,但實際上我不知道他們需要與否。發生
<%= form_for @account do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :currency %><br />
<%= select_tag(:currency, options_from_collection_for_select(Currency.all, :id, :name),\
:id => "account_currency_id", :name => "account[currency][id]", :prompt => "Выберите валюту...")%>
</div>
<div class="actions">
<%= f.submit "Сохранить" %>
</div>
<% end %>
,當我試圖箱帳戶錯誤:美元,歐元,盧布
class Currency < ActiveRecord::Base
has_many :accounts
attr_accessible :id
accepts_nested_attributes_for :accounts
end
所以在帳戶形式我有一個貨幣選擇框 - 即有3個項目的另一個模型貨幣:
ActiveRecord::AssociationTypeMismatch in AccountsController#create
Currency(#52889580) expected, got ActiveSupport::HashWithIndifferentAccess(#28841960)
請求參數:
{"utf8"=>"✓",
"authenticity_token"=>"VfCshuGyldoI5Q5DThT/RDpwewCh91apgsnmxyppWqI=",
"account"=>{"name"=>"Основной наличный счет",
"currency"=>{"id"=>"3"}},
"commit"=>"Save"}
如果我嘗試從標識手動查找貨幣:
param = params[:account]
param[:currency] = Currency.find(param[:currency][:id])
@account = Account.new(param)
有由巫名稱一個新的錯誤不存在。我不喜歡我應該手動設置:id => "account_currency_id", :name => "account[currency][id]"
,因爲默認情況下它們都是「貨幣」。 Rails 3.1
非常感謝。此外,我的問題是,帳戶有列'貨幣'沒有'_id',所以我加了它,它現在正常工作。 – zishe
很高興能聽到:) – DanneManne