accepts_nested_attributes_for with has_many => :through Options

后端 未结 7 1945
陌清茗
陌清茗 2020-12-08 10:10

I have two models, links and tags, associated through a third, link_tags. The following code is in my Link model.

Associations:

class Link < Acti         


        
相关标签:
7条回答
  • 2020-12-08 10:45

    Take a look at the line of your code

    <% f.fields_for :tags_attributes do |tag_form| %>
    

    You need to use just :tags instead of :tags_attributes. This will solve your issue

    Make sure that You have build links and tags in your controller like

    def new
      @link = @current_user.links.build
      @link.tags.build
    end
    
    0 讨论(0)
  • 2020-12-08 10:47

    In order for this to work, you need to pass in the right params hash:

    params = {
      :link => {
        :tags_attributes => [
          {:tag_one_attr => ...}, {:tag_two_attr => ...}
        ],
        :link_attr => ...
      }
    }
    

    And your controller will look like:

    def create
      @link = Link.create(params[:link]) # this will automatically build the rest for your
    end
    
    0 讨论(0)
  • 2020-12-08 10:49

    I found this here on stackoverflow:

    Rails nested form with has_many :through, how to edit attributes of join model?

    please tell me if it worked.

    0 讨论(0)
  • 2020-12-08 10:57

    In your controller in the new action (that loads the form partial), are you building a @tag through your link?

    So you should see something along the lines of:

    @link = Link.new
    @tag = @link.tags.build
    

    It might be best to post the contents of the new and create action of your links_controller.

    0 讨论(0)
  • 2020-12-08 11:01

    Try this:

    <% f.fields_for :tags_attributes do |tag_form| %>
    
    0 讨论(0)
  • 2020-12-08 11:06

    try

    <% f.fields_for :tags do |tag_form| %> 
    

    (ie lose the _attributes in :tag_attributes) That's how I've usually done nested forms

    0 讨论(0)
提交回复
热议问题