를 통해 속성 :보기에레일 내가 다음과 같은 정보와 레일 5.1 응용 프로그램 실행하고 양식
모델
class Company < ApplicationRecord
has_many :complaints
accepts_nested_attributes_for :complaints
validates :name, presence: true
end
class Complaint < ApplicationRecord
belongs_to :company
validates :username, :priority, presence: true
end
컨트롤러
class ComplaintController < ApplicationController
def new
@company = Company.new
@company.complaints.build
end
def create
@company = Company.new(company_params)
respond_to do |format|
if @company.save
format.html { redirect_to complaint_url }
else
format.html { render :new }
end
end
end
private
def company_params
params.require(:company).permit(:name, complaints_attributes: [:username, :priority])
end
양식을
<%= form_for @company do |f| %>
<%= f.label :name, "Company" %>
<%= f.text_field :name, type: "text" %>
<%= f.fields_for :complaints do |complaint| %>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
내가 ave는 양식의 complaint_attributes
부분에 대한 하나의 입력 필드입니다 (즉, 위의 그림과 같이 사용자 이름 필드와 우선 순위 필드는 각각 하나만 사용).
양식에서 사용자 이름/우선 순위에 대해 여러 개의 입력란을 사용하려는 경우 하나의 제출에서 여러 사용자 이름/우선 순위 조합을 제출할 수 있도록 양식을 제출하면 마지막 사용자 이름/우선 순위 만 저장됩니다. 양식의 값. 이 뷰의 예는 다음과 같습니다
<%= form_for @company do |f| %>
<%= f.label :name, "Company" %>
<%= f.text_field :name, type: "text" %>
<%= f.fields_for :complaints do |complaint| %>
<div>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
</div>
<div>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
</div>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
내가 양식을 제출하면, 내가 (단일 불만 제출에 대한)이 같은 해시를 얻을 것으로 나타났습니다 :
{"utf8"=>"✓", "authenticity_token"=>"...", "company"=>{"name"=>"Test", "complaints_attributes"=>{"0"=>{"username"=>"test_person", "priority"=>"1"}}}, "commit"=>"Submit"}
을 수정할 수있는 방법이 있나요 params 객체를 파라미터는이에이 유사하고는 DB?
{"utf8"=>"✓", "authenticity_token"=>"...", "company"=>{"name"=>"Test", "complaints_attributes"=>{"0"=>{"username"=>"test_person", "priority"=>"1"}"1"=>{"username"=>"test_person", "priority"=>"2"}}}, "commit"=>"Submit"}
하거나하지 않은 경우 저장해야합니다 bove, 단일 양식에서 여러 필드를 사용하는 경우 사용자 이름/우선 순위 값을 저장하는 가장 좋은 방법은 무엇입니까?
편집 : 필요에 따라 사용자 이름/우선 순위 필드 그룹을 동적으로 추가 할 수 있으므로 설정 한 번호로 제한하고 싶지는 않습니다.
FYI 편집하면 완전히 다른 질문이됩니다. – gabrielhilal
예 - 지적하지 않은 것에 대해 사과드립니다. 나는 첫 번째 답이 게시 되 자마자 그것을 깨달았다. – Wes