कई के माध्यम से नेस्टेड विशेषताओं को सहेजते समय त्रुटि मौजूद होनी चाहिए

Jan 21 2021

रेल 6 में कई-से-कई एसोसिएशन के माध्यम से नेस्टेड रिकॉर्ड को बचाने की कोशिश की जा रही है, लेकिन "टैग मौजूद होना चाहिए" त्रुटि। टैग post_tags के लिए एक अभिभावक है जो पोस्ट और टैग (कई-कई) के बीच क्रॉस संदर्भ तालिका है। मैं क्या करना चाहता हूं, जब एक नया पोस्ट बनाया जाता है, पोस्ट फॉर्म पर चयनित टैग से संबंधित पोस्ट_टैग रिकॉर्ड सहेजें। मैंने कुछ संबंधित पोस्टों को देखा: यहाँ और यहाँ , और inverse_of का उपयोग करने की कोशिश की, ऑटोसैव: सच, और वैकल्पिक: सच, लेकिन वे काम नहीं कर रहे हैं।

यहाँ मेरे पास क्या है:

मॉडल

class Post < ApplicationRecord
  has_many :post_tags, dependent: :destroy, inverse_of: :post, autosave: true
  has_many :tags, through: :post_tags
end

class PostTag < ApplicationRecord
  belongs_to :post
  belongs_to :tag
end

class Tag < ApplicationRecord
  has_many :post_tags, dependent: :destroy, inverse_of: :tag, autosave: true
  has_many :posts, through: :post_tags
end

नियंत्रण करनेवाला

PostsController < ApplicationController
  def new
    @post = Post.new
    @tags= Tag.all
    @post.post_tags.build
  end

  def create
    @post = Post.new(post_params)
    @post.post_tags.build
    
    if @post.save
      ...
    end
  end
  
  private

  def post_params
        params.require(:post).permit(:title, :content, :user_id, post_tags_attributes: [tag_id: []])
  end
end

प्रपत्र

<%= f.fields_for :post_tags do |builder| %>
    <%= builder.collection_check_boxes :tag_id, Tag.top_used, :id, :name, include_hidden: false %>
<% end %>

त्रुटि

   (0.4ms)  ROLLBACK
  ↳ app/controllers/posts_controller.rb:229:in `create'
Completed 422 Unprocessable Entity in 41ms (ActiveRecord: 3.7ms | Allocations: 15178)


  
ActiveRecord::RecordInvalid (Validation failed: Post tags tag must exist):

जवाब

1 max Jan 21 2021 at 23:36

आपको "मॉडल से जुड़ने" के उदाहरण बनाने की जरूरत नहीं है। आपको बस tag_ids=द्वारा बनाए गए सेटर में एक सरणी पास करनी होगी has_many :tags, through: :post_tags

<%= form_with(model: @post) %>
  ...
  <div class="field">
    <%= f.label :tag_ids %>
    <%= f.collection_check_boxes :tag_ids, @tags, :id, :name %>
  </div>
  ...
<% end %>

आपका नियंत्रक ऐसा दिखना चाहिए:

PostsController < ApplicationController
  def new
    @post = Post.new
    @tags = Tag.all
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post, status: :created
    else
      @tags = Tag.all
      render :new
    end
  end
  
  private

  def post_params
        params.require(:post)
              .permit(:title, :content, :user_id, tag_ids: [])
  end
end

सम्मिलित मॉडल उदाहरण बनाने के लिए नेस्टेड विशेषताओं और फ़ील्ड_ के लिए उपयोग करना वास्तव में केवल तभी आवश्यक है जब आपको शामिल मॉडल में अतिरिक्त जानकारी संग्रहीत करने की आवश्यकता होती है।