我没有得到预期的结果,技能没有得到保存。我想让每个人都说一个主要技能只有 1。
D B
# Table name: people
#
# id :integer not null, primary key
# first_name :string(255)
# last_name :string(255)
# headline :string(255)
# description :string(255)
# user_id :integer
# created_at :datetime
# updated_at :datetime
#
# == Schema Information
#
# Table name: skills
#
# id :integer not null, primary key
# title :string(255)
# description :text
# created_at :datetime
# updated_at :datetime
#
# == Schema Information
#
# Table name: entity_skills
#
# id :integer not null, primary key
# skill_id :integer
# person_id :integer
# created_at :datetime
# updated_at :datetime
#
楷模
class Person < ActiveRecord::Base
has_many :entity_skills
has_many :skills, through: :entity_skills, foreign_key: "person_id"
accepts_nested_attributes_for :skills
end
class Skill < ActiveRecord::Base
has_many :entity_skills
has_many :people, through: :entity_skills, foreign_key: "person_id"
end
class EntitySkill < ActiveRecord::Base
belongs_to :person
belongs_to :skill
end
控制器
def new
@person = Person.new
@all_skills = Skill.all
@entity_skills = @person.skills.build
end
def edit
@all_skills = Skill.all
@entity_skills = @person.entity_skills.build
end
def create
@person = Person.new(person_params)
respond_to do |format|
if @person.save
format.html { redirect_to @person, notice: 'Person was successfully created.' }
format.json { render action: 'show', status: :created, location: @person }
else
format.html { render action: 'new' }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
def person_params
params.require(:person).permit(:first_name, :last_name, :headline, :description, :user_id, :employer_id, skills_attributes: [:id])
end
形式
<%= form_for(@person) do |f| %>
....
....
<h2>Skills</h2>
<%= f.fields_for @entity_skills do |es| %>
<%= es.label "All Skills" %>
<%= collection_select(:skills, :id, @all_skills, :id, :title) %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
没有为技能保存任何内容,有人可以解释发生了什么吗?