fields_for geting_nested_attributes_for re afleds_to 관계
-
19-09-2019 - |
문제
나는 레일 전망에서 belongs_to
새로운 것을 사용한 관계 accepts_nested_attributes_for
레일 시설 2.3. 사용 가능한 많은 리소스를 확인했는데 내 코드처럼 보입니다. ~해야 한다 일하고 있지만 fields_for
나에게 폭발하고, 중첩 모델을 구성하는 방식과 관련이 있다고 생각합니다.
내가 쳤던 오류는 많은 원인을 가질 수있는 일반적인 오류입니다.
'@account[owner]' is not allowed as an instance variable name
다음은 관련된 두 가지 모델입니다.
class Account < ActiveRecord::Base
# Relationships
belongs_to :owner, :class_name => 'User', :foreign_key => 'owner_id'
accepts_nested_attributes_for :owner
has_many :users
end
class User < ActiveRecord::Base
belongs_to :account
end
아마도 계정에 '소유자'를 가질 수 있고 '사용자'를 가질 수 있지만 사용자는 사용자 모델 계정 _id 키를 기반으로 하나의 '계정'만 가지고 있기 때문에 내가 'rong'을하고있는 곳 일 것입니다.
이것은 New.html.haml의보기 코드입니다.
- form_for :account, :url => account_path do |account|
= account.text_field :name
- account.fields_for :owner do |owner|
= owner.text_field :name
그리고 이것은 새로운 조치의 컨트롤러 코드입니다.
class AccountsController < ApplicationController
# GET /account/new
def new
@account = Account.new
end
end
로드 /계정 /신규를 시도하면 다음과 같은 예외가 발생합니다.
NameError in Accounts#new
Showing app/views/accounts/new.html.haml where line #63 raised:
@account[owner] is not allowed as an instance variable name
신비한 '빌드'방법을 사용하려고하면 컨트롤러에서 폭탄이 나옵니다. 아마도 빌드가 다중 레코드 관계를위한 것이기 때문일 것입니다.
class AccountsController < ApplicationController
# GET /account/new
def new
@account = Account.new
@account.owner.build
end
end
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.build
컨트롤러에서 @ac 변수 이름 ".
다른 사람이 새로운 acccept_nested_attributes_를 가지고있는 사람이 있습니까? 특별하거나 다른 일이 있습니까? 모든 공식 예제 및 샘플 코드 (예 : Ryans Scraps에서 훌륭한 물건)는 다중 레코드 협회와 관련이 있습니다.
해결책
나는 당신을 생각합니다 accepts_nested_attributes
관계의 반대편에 있습니다. 아마도 이런 것이 효과가 있을까요?
class Account < ActiveRecord::Base
belongs_to :owner, :class_name => 'User', :foreign_key => 'owner_id'
has_many :users
end
class User < ActiveRecord::Base
belongs_to :account
has_one :account, :foreign_key => :owner_id
accepts_nested_attributes_for :account
end
계정을 구축하려면 build_account를 사용하려고합니다.
더 많은 예제를 볼 수 있습니다 문서.
다른 팁
나는 몇 달이 너무 늦었지만이 오류를 해결하려고했고 내 상황은 '다른 방식으로 직면하는 관계를 바꿀 수 없다는 것이 었습니다.
대답은 정말 간단합니다. 새로운 조치 에서이 작업을 수행해야합니다.
@account.build_owner
Fields_for를 사용하여 양식이 표시되지 않은 이유는 유효한 객체가 없기 때문입니다. 당신은 다음과 같이 올바른 아이디어를 가지고있었습니다.
@account.owner.build
그러나 이것은 방법이 아닙니다 belongs_to
일하다. 이 방법은 만 생성됩니다 has_many
그리고 has_and_belongs_to_many
.
참조:http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference
레일 2.3.5를 사용하고 있는데 같은 것을 발견했습니다. active_record의 nested_attributes.rb 소스를 확인하면 속성이 잘 작동하는 것처럼 보입니다. 따라서 "중첩 된 형태"버그 인 것 같습니다.
나는 당신과 똑같은 중첩 된 형태를 가지고 있습니다. User belongs_to :address
, 그리고 Address
사용자와 무관합니다.
그런 다음 형태로, 나는 그냥한다 <% f.fields_for :address_attributes do |address_form| %>
대신에 <% f.fields_for :address do |address_form| %>
. 더 나은 방법이있을 때까지 임시 해킹이지만 이것은 작동합니다. 방법 accepts_nested_attributes_for
매개 변수는 다음과 같은 것을 포함 할 것으로 기대하고 있습니다.
{user=>{address_attributes=>{attr1=>'one',attr2=>'two'}, name=>'myname'}
...하지만 fields_for
생산 :
{user=>{address=>{attr1=>'one',attr2=>'two'}, name=>'myname'}
이렇게하면 추가 할 필요가 없습니다 has_one :account
내 경우에는 작동하지 않는 코드에.
업데이트 : 더 나은 답변을 찾았습니다.
다음은이 작업을 올바르게하기 위해 사용하는 코드의 요지입니다.
도움이되기를 바랍니다.
class Account < ActiveRecord::Base
belongs_to :owner :class_name => 'User', :foreign_key => 'owner_id'
end
그것은 나를 위해 작동합니다. : foreign_key => '소유자 _id'가 제 경우에 핵심 문제였습니다.