0

In my rails application I've two models called 'user' and 'store'. An user belongs_to store and A store has_many users.An user has many attributes like name,email and role etc.,. In one of the forms for store, I want to use nested forms to create users whose role is packer . The Problem is when I use nested forms, other users whose role is not 'packer' are also listed. I specifically want to use nested forms only for users whose role is 'packer'. Is there any way to filter users with role as 'packer' in nested forms

1 Answer 1

1

To start with you may want to setup a "short-cut" relationship:

class Store < ActiveRecord::Base
  has_many :users
  has_many :packers, -> { where(role: 'packer') }, class_name: 'User'
end

class User < ActiveRecord::Base
  belongs_to :store
end

fields_for(record_name, record_object = nil, options = {}, &block) takes an optional record_object argument that lets you set the records used:

<%= form_for @store do |f| %>
  ...
  <%= f.fields_for :users, f.object.packers do |user| %>
    <%= user.hidden_field :role %>
    <%= user.text_field :name %>
  <% end %>
  ...
<% end %>

Using f.object is not strictly necessary - you could use any variable, but it does make it easier to build reusable partials.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.