'accepts_nested_attributes'의 반대를하려고합니다. 'children_controller # create'에서 부모 인스턴스를 만들고 싶습니다. 어쩌면 당신은 약간의 충고를하거나 나에게 그렇게하는 것이 적절하지 않다고 설명 할 것입니다. 나는 모든 의견에 열려 있습니다!레일 - 하위 폼에서 부모 인스턴스 만들기
class Client < ActiveRecord::Base
has_one :magazine
validates :name, presence: true, uniqueness: true
end
그리고 잡지 모델 :
나는 클라이언트 모델이
class Magazine < ActiveRecord::Base
belongs_to :client
validates :client, :launch_date, presence: true
# accepts_nested_attributes_for :client
end
내가 사용을 보석 레일 반응 /magazines
에 내가 가진 새로운 잡지를 제작하는 형태를 갖는다 클라이언트 이름을 제공하는 텍스트 필드.
PG::ForeignKeyViolation - ERROR: insert or update on table "magazines" violates foreign key constraint "fk_rails_cd907cfe6d"
DETAIL: Key (client_id)=(51) is not present in table "clients".
클라이언트가 데이터베이스에 저장하지 않은 것처럼 내 magazines_controller.rb
에서
은 내가 항상 PG :: 오류와 끝까지 다음
def create
@client = Client.find_by_name(magazine_params[:client_id])
@selected_magazine = Magazine.new(magazine_params)
authorize @selected_magazine
if @client
@selected_magazine.client = @client
else
@client = Client.new(name: magazine_params[:client_id])
@client.save
@selected_magazine.client = @client
end
# @client = Client.where(name: magazine_params[:client_id]).first_or_create
# @selected_magazine.client = @client if @selected_magazine.client_id.to_i == 0
@title = magazine_params[:title]
@selected_issue = nil
@issues = nil
@selected_magazine.save
binding.pry
@magazines = policy_scope(Magazine)
end
def magazine_params
magazine_params = params.require(:magazine).permit(:title, :analytics_id, :launch_date, :client_id)
# if @client
# params[:magazine][:client_id] = @client.id
# magazine_params.merge!(params[:magazine])
# end
return magazine_params
end
을 넣어. 내가 binding.pry
이고 Client.all
after @client.save
으로 전화하면 내 새 클라이언트가 반환되지 않습니다.
나는 다른 프로젝트에서 유사한 문제가 있었기 때문에 약간 놀랐다. 그렇게하는 것이 잘 작동했다. 귀하의 정보 :
# Previous Project
# Gemfile.lock
pg (0.18.3)
rails (4.2.0)
#Current Project
# Gemfile.lock
pg (0.18.4)
rails (4.2.5.1)
미리 도움을 주셔서 감사합니다. children_controller의 자식보다 먼저 부모 인스턴스를 만드는 좋은 방법에 대한 조언이 있으면 정말 흥미 롭습니다.
PS1 : 컨트롤러에서 나는 먼저 주석 처리를 시도했으나 생성은 여전히 동일합니다. PS2 : Gemfile에 대한 추가 정보가 필요하면 알려주세요.
실제 구현을 위해 이것을 참조 할 수 있습니까? 중첩 된 속성을 받아들이는 이온. https://www.sitepoint.com/complex-rails-forms-with-nested-attributes/ –
먼저 'Client' 인스턴스를 가져오고 이전 구문 인'Client '는 사용하지 마십시오. 'Client.where (이름 : magazine_params [: client_id]). 첫 번째! ' 둘째,'Client' 인스턴스가 저장되어 있는지 확인하고,'Client' 인스턴스 @ client.save!'라고합니다. – BitOfUniverse
@VaibhavDhoke, 부모에서 자식으로가는 중첩 된 특성의 역함을 시도합니다. [link (http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html). 내가 당신의 예를 든다면 일대일 연결을 사용하여 주소 형식으로 사용자를 만들고 싶습니다. – MaxDpt