accepts_nested_attributes_for with has_many => :through Options

六眼飞鱼酱① 提交于 2019-11-28 05:50:37
Jyothu

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
Tiago

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.

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

Try this:

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

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.

try

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

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

You need to build a tag in your controller or in the view

def new
  @link = @current_user.links.build
  @link.tags.build
end

#in your view you can just use the association name
<% f.fields_for :tags do |tag_form| %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!