【问题标题】:Rails Nested Attributes with has_many through association not creating通过关联未创建具有 has_many 的 Rails 嵌套属性
【发布时间】:2018-02-28 18:16:22
【问题描述】:

我正在尝试提供一种方法,使用 has_many through 关系(通过“分组”)在一个模型中生成新对象(“列表”),并在另一个模型(“项目”)中生成新的关联对象。我能够使表单正常工作,但无法弄清楚我缺少什么才能正确完成创建过程。

Rails v. 5.1.2,Ruby v. 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 %>

控制台输出示例

在 2017-09-19 13:12:53 -0700 为 127.0.0.1 开始 POST "/lists" ListsController#create 作为 HTML 处理 参数:{"utf8"=>"✓", "authenticity_token"=>"Y6rszWVUXDIVymuoBkXwvkw1pVbyC6mffiWIZzr7PVd1NT9JJi6rD72k5Fh2qU5Q5tEd0qn6bFYMSJnz2TgjAA==", "list"=>{"title"=>"网站", "items_={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) 开始 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) 提交 重定向到http://localhost:3000/lists/24 完成 302 Found in 7ms (ActiveRecord: 1.6ms)

显然,我仍在学习 - 但是在尝试了这个论坛上的各种相关提示后,我无法弄清楚这一点。感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails activerecord associations ruby-on-rails-5.1


    【解决方案1】:

    您快到了,但控制台日志中报告了一个错误:Unpermitted parameter: :items_attributes

    在您的list_params 中将item_attributes 更改为items_attributes

    def list_params
      params.require(:list)
            .permit(:title, items_attributes: [:id, :title, :url])
    end
    

    【讨论】:

      【解决方案2】:

      在定义参数时,您的语法有一些错误。应该是这样的:(项目而不是项目,你不需要{})

      def list_params
        params.require(:list).permit(:title,
        items_attributes: [:id, :title, :url])
      end
      

      【讨论】:

      • 成功了......我明白了 - 我还必须删除验证“has_lists?”在 item.rb 模型中,以使此配置工作。你太棒了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 2021-08-12
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多