ruby-on-rails - 更新时 Rails 4 嵌套属性多条记录

标签 ruby-on-rails ruby nested ruby-on-rails-4

我卡住了,我不知道为什么它不能正常工作。 我有一个模型产品,它有很多标签。 当我更新产品 rails 时,会正确更新产品属性,但会创建另一个标签记录,而不是仅仅更新它。

这是我的代码:

查看表单:

 <%= form_for ([@product.user, @product]), id: 'edit_form' do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
    
      <div class="field">
        <%= f.label :name %><br>
        <%= f.text_field :name %>
      </div>
      <div class="field">
        <%= f.label :description %><br>
        <%= f.text_area :description %>
      </div>
    
      <div class="field">
        <%= f.fields_for :tags do |t| %>
          <%= t.label :name %>
          <%= t.text_field :name %>
        <% end %>
      </div>
    
    
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

产品型号:

 class Product < ActiveRecord::Base
    
      belongs_to :user, :foreign_key => "user_id"
      has_many :tags, :dependent => :destroy
      accepts_nested_attributes_for :tags, reject_if: :all_blank, allow_destroy: true, :update_only => true
    end

标签模型:

 class Tag < ActiveRecord::Base
        belongs_to :product, :foreign_key => "product_id"
        # before_save { name.downcase! }
    
    end

产品负责人:

 def edit
        user = User.find(params[:user_id])
        @product = user.products.find(params[:id])
        @tags = @product.tags.all
    
      respond_to do |format|
            format.html
            format.js
        end 
      end
    
      def update
          user = User.find(params[:user_id])
          @product = user.products.find(params[:id])
          @tags = @product.tags.all
        
        respond_to do |format|
          if  @product.update(product_params)
            format.html { redirect_to([@product.user, @product], :notice => 'Product successfully updated.') }
          else
            format.html { render :action => "edit" }
          end
        end
      end

    def product_params
          params.require(:product).permit(:name, :description, tags_attributes: :name)
        end

最佳答案

您必须在 Controller 的许可参数中传递标签 ID

def product_params
  params.require(:product).permit(:name, :description, tags_attributes: [:id,:name])
end

关于ruby-on-rails - 更新时 Rails 4 嵌套属性多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565296/

相关文章:

ruby-on-rails - 错误 : heartbeat: Connection lost (ECONNRESET) in sidekiq

ruby-on-rails - Ruby on Rails 与 Redis,I18n 键值后端

ruby - 立即从控制台获取单个字符

ruby - 在 Ruby 中将字符串转换为 JSON

json - Swift - JSON 嵌套结构获取具有相同键名的所有值

<label> 内的 HTML 标签

ruby-on-rails - 如何使用 minitest 测试 ssl 是否强制执行?

css - 防止描述列表项在缺少值时折叠

mysql - SQLite3::SQLException:没有这样的列:parameters.user:

python - 在 Python 中确定嵌套元组的嵌套级别的简单方法