我想提供一種方法來生成一個新的對象(「列表」)與一個新的關聯對象在另一個(「項目」)使用has_many通過關係(通過「分組」)。我能夠讓表單正常工作,但無法弄清楚我錯過了什麼,以便正確完成創建過程。Rails嵌套屬性與has_many通過關聯不創建
Rails的訴5.1.2,紅寶石訴2.4.1
lists_controller.rb
def new
@list = current_user.lists.new
3.times { @list.items.build }
end
def create
@list = current_user.lists.new(list_params)
respond_to do |format|
if @list.save
format.html { redirect_to @list, notice: 'List was successfully created.' }
format.json { render :show, status: :created, location: @list }
else
format.html { render :new }
format.json { render json: @list.errors, status: :unprocessable_entity }
end
end
end
private
def set_list
@list = List.find(params[:id])
end
def correct_user
@list = current_user.lists.find_by(id: params[:id])
redirect_to lists_path, notice: "Not authorized to edit this list"
if @list.nil?
end
def list_params
params.require(:list).permit(:title, {
item_attributes: [
:id, :title, :url
]})
end
items_controller.rb
def new
@item = Item.new
end
private
def set_item
@item = Item.find(params[:id])
end
def item_params
params.require(:item).permit(:title, :body, :url, :created,
:list_ids => [])
end
end
list.rb模型
個has_many :groupings, :dependent => :destroy
has_many :items, :through => :groupings
accepts_nested_attributes_for :items,
reject_if: ->(attrs) { attrs['title'].blank? || attrs['url'].blank? }
item.rb的模型
has_many :groupings, :dependent => :destroy
has_many :lists, :through => :groupings
validate :has_lists?
accepts_nested_attributes_for :lists
attr_writer :list_titles
after_save :assign_lists
def list_titles
@list_titles || lists.map(&:title).join(' ')
end
private
def assign_lists
if @list_titles
self.lists = @list_titles.split(/\,/).map do |title|
if title[0..0]==" "
title=title.strip
end
title=title.downcase
List.find_or_create_by_title(title)
end
end
end
def has_lists?
errors.add(:base, 'This item needs to be assigned to a list before it can be saved.') if self.lists.blank?
end
grouping.rb模型
belongs_to :item
belongs_to :list
accepts_nested_attributes_for :item, :list
詞典表格
<%= form_with(model: list, local: true) do |f| %>
<% if list.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(list.errors.count, "error") %> prohibited this list from being saved:</h2>
<ul>
<% list.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title, id: :list_title %>
</div>
<div>
<p><strong>Items:</strong></p>
<%= f.fields_for :items do |item| %>
<div>
<%= item.label :title %>
<%= item.text_field :title %>
<%= item.label :url %>
<%= item.text_field :url %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
樣品控制檯輸出
開始POST 「/列表」 爲127.0.0.1,在2017年9月19日十三點12分53秒-0700 處理由ListsController#創建作爲HTML 參數:{ 「UTF8」 =>「✓」,「authenticity_token」=>「Y6rszWVUXDIVymuoBkXwvkw1pVbyC6mffiWIZzr7PVd1NT9JJi6rD72k5Fh2qU5Q5tEd0qn6bFYMSJnz2TgjAA ==」,「list」=> {「title」=>「網站」,「items_attributes」=> {「0」=> {「title」=> Google「,」url「=>」www.google.com「},」1「=> {」title「=>」Yahoo「,」url「=>」www.yahoo.com「},」2「= > {「title」=>「Bing」,「url」=>「www.bing.com」}}},「commit」=>「創建列表」} 用戶負載(0.3ms)SELECT「users」。* FROM「users」WHERE「users」。「id」= $ 1 ORDER BY「users」。「id」ASC LIMIT $ 2 [[「id」,2],[「LIMIT」,1]] 不允許的參數:items_attributes (0.1ms)BEGIN SQL(0.9ms)INSERT INTO「lists」(「title」,「created_at」,「updated_at」,「user_id」)VALUES($ 1,$ 2,$ 3,$ 4) RETURNING「id」[[「title」,「Websites」],[「created_at」,「2017-09-19 20:12:53.458577」],[「updated_at」,「2017-09-19 20:12:53.458577 「],[」 user_ID的」,2] (0.3ms的)COMMIT 重定向到http://localhost:3000/lists/24 完成302發現在7毫秒(ActiveRecord的:1.6毫秒)
我還在學習,清楚 - 但嘗試之後這個論壇上的各種相關提示我無法弄清楚這一點。謝謝你的幫助!
這奏效了....我得到它 - 我也不得不刪除驗證「has_lists?」在item.rb模型中,以便使此配置有效。你太棒了。 – dstep
對,你也必須刪除它。很好的接收 –