Question

I have Account model which have a has_many relationship with User model:

class Account < ActiveRecord::Base
  has_many :users, -> { uniq }
  accepts_nested_attributes_for :users


class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :account

I added avatar attribute to User model using paperclip.

I want each user to have access to the common account settings, and inside it having the possibility to upload his/her own avatar.

I use simple_form so I tried this:

<%= simple_form_for current_account, :html => { :multipart => true } do |f| %>

    <%# here come account settings %>
    <%= f.input :time_zone, :label => t(".timezone"), 
                 :
                 :

    <%# here I need to access current user attributes %>
    <%= f.simple_fields_for :user, current_account.users.first do |user_form| %>
        <%= user_form.file_field :avatar, :error => false %>
    <% end %>

<% end %>

First problem:
I need some logic to access current_user instead of current_account.users.first. Since there is a superadmin which can access all accounts, use current_user is not enough.

Second (and bigger) problem:
I added in my controller the avatar parameter to the whitelist:

def allowed_params
  params.require(:account).permit(:time_zone, :logo, :description, user: [:avatar])
end

When I try to update my model:

if current_account.update(allowed_params)

I get this error:

unknown attribute: user

I also tried:

params.require(:account).permit(:language, :time_zone, :logo, :description, :user_attributes => [:avatar])

and:

params.require(:account).permit(:language, :time_zone, :logo, :description, :users_attributes => [:avatar])

(in plural)

but since I use ActionController::Parameters.action_on_unpermitted_parameters = :raise I get:

found unpermitted parameters: user

It must be something very easy, some help please?

Was it helpful?

Solution

Ok, got it!!

The problem is the one-to-many relationship and the way I tried to access a single instance of user. The correct way to do it is:

<% current_account.users.each_with_index do |user, index|%>
    <%= f.simple_fields_for :users, user do |user_form| %>
        <%= user_form.file_field :avatar, :error => false %>
    <% end %>
<% end %>

As you can see, the iteration should be done over the relation, and only when having a single instance "in hand" we can user the simple_fields_for.

Also, notice that the first parameter passed to simple_fields_for is :users and not :user, since this is a one-to-many relationship.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top