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
Add a comment
|
1 Answer
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.