Torrm
Torrm

Reputation: 153

Rails Nested Attributes for a Model not directly associated

I am building a feature whereby several models (3+) will have images or documents associated with them. To reduce duplicate code I have created a single model MediaUploads which belongs_to :user resulting in a user has_many :media_uploads.

The MediaUploads table stores the User ID alongside file information, nothing specific to any other model. Whereby each model that requires an image has the association has_one :media_upload and a reference column on their DB table t.integer "media_uploads_id. I think this is an appropriate way to achieve this however I am running into a few problems.

The above setup works fine if a User is managing their media however I am struggling to make this work using nested forms. An example, Post which may require a MediaUpload may look like this:

accepts_nested_attributes_for :media_upload now if I use byebug and get the params I can see the file details was included ActionController::Parameters {"media_uploads"=>{"filename"=>#<... but using post_params I can see that it was not permitted. I have added this to the strong params like so: ...post attributes..., media_upload_attributes: [ :filename ] - I have also tried just media_upload and media_uploads.

My Googling keeps bringing me back to changing the new method to something like:

@post = Post.new @post.build_media_upload

which gives me the error unknown attribute 'post_id' for MediaUpload. - presumably because the build needs to happen from the user, considering the user_id is referenced by MediaUpload

Would anybody be able to give me some pointers?

UPDATE

This is what I have currently that is not working:

In my Post.rb I have the following

has_one :media_upload
accepts_nested_attributes_for :media_upload

In my _form.html.erb I have

<%= f.fields_for :media_uploads do |h| %>
  <%= h.file_field :filename, class:"btn-file" %>
<% end %>

In my Controller I have

..post params..., media_uploads_attributes: [ :filename ])

I can see the data when using the terminal command params however post_params states the following: Unpermitted parameter: media_uploads

Upvotes: 0

Views: 392

Answers (1)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

It should be plural in strong params, because Rails looks at the database table, not your model and database tables are named in plural.

So result should be:

...post attributes..., media_uploads_attributes: [ :filename ]

Upvotes: 1

Related Questions