I tried to validate associated attribute access_module_id
in role
model but it doesn't work. How to give validation of presence: true
to other model's attribute in role
form? Here is associations
role.rb
class Role < ActiveRecord::Base
....
has_many :access_module_roles, :dependent => :destroy
has_many :access_modules, through: :access_module_roles
validates :name,:access_module_id, presence: true # I want to validate presence of access_module_ids in role form
end
access_module.rb
class AccessModule < ActiveRecord::Base
has_many :access_module_roles
has_many :roles, through: :access_module_roles
end
access_module_roles.rb
class AccessModuleRole < ActiveRecord::Base
belongs_to :access_module
belongs_to :role
end
Update
I have tried below validation and if I select one, two or all still getting an error like "Access module ids can't be blank"
validates_presence_of :access_module_ids
Controller
def create
@role = Role.new(role_params)
respond_to do |format|
if @role.save
params[:role][:access_module_ids].each do |acmi|
AccessModuleRole.create!(:role_id => @role.id, :access_module_id => acmi) if acmi!=""
end
format.html { redirect_to roles_path, notice: 'Role was successfully created.' }
format.json { render :index, status: :created, location: @role }
else
format.html { render :new }
format.json { render json: @role.errors, status: :unprocessable_entity }
end
end
end